-
-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Description
Symfony version(s) affected
All
Description
The current implementation or UrlGenerator
works if you have a path specified for every locale.
For example if you have a route like this:
#[Route(
path: [
'en' => '/{_locale}/test-route',
'de' => '/{_locale}/test-route',
],
name: 'test_route',
requirements: ['_locale' => 'en|de|...'],
)]
Internally it creates two routes:
test_route.en
test_route.de
and everything works as expected since before generating a route the UrlGenerator uses the fallback locale if one is not specified and finds the correct route.
The problem is if you for example have a lot of languages and do not want to localize the path for every language and you have routes defined like this:
#[Route(
path: '/{_locale}/test-route',
name: 'test_route',
requirements: ['_locale' => 'en|de|...'],
)]
In this case test_route.en
does not exist and the generator tries to generate a route and fails if the _locale
part is missing.
For handling code that is part of a web request this still works since _locale
is set in the RequestContext
by Symfony\Component\HttpKernel\EventListener::onKernelRequest()
, unfortunately this is not executed for code that is running as a console application or when performing tests by booting the Kernel and fetching a service from it.
How to reproduce
Create a route like this:
#[Route(
path: '/{_locale}/test-route',
name: 'test_route',
requirements: ['_locale' => 'en|de'],
)]
Inject an UrlGeneratorInterface into a Console application and try to generate a link with $router->generate('test_route')
and you will get an Exception:
[Symfony\Component\Routing\Exception\MissingMandatoryParametersException]
Some mandatory parameters are missing ("_locale") to generate a URL for route "test_route".
Possible Solution
It would be nice if setting default_locale
would work consistently or at least allow us to set the default parameters for the context the same way we can set router.request_context.host
or router.request_context.scheme
(I've tried settings router.request_context.parameters
but for some reason it didn't work and I didn't investigate further).
Additional Context
No response