I created an application which was not intended to have translations, but now I decided to add this feature. The problem is that all my routes look like this:
The better solution instead of putting requirements in all routes or global scope is to use EventListener and redirect user into same route, but with supported locale, in example:
router = $router;
$this->defaultLocale = $defaultLocale;
$this->supportedLocales = $supportedLocales;
$this->localeRouteParam = $localeRouteParam;
}
public function isLocaleSupported($locale) {
return in_array($locale, $this->supportedLocales);
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$locale = $request->get($this->localeRouteParam);
if(null !== $locale) {
$routeName = $request->get('_route');
if(!$this->isLocaleSupported($locale)) {
$routeParams = $request->get('_route_params');
if (!$this->isLocaleSupported($this->defaultLocale))
throw \Exception("Default locale is not supported.");
$routeParams[$this->localeRouteParam] = $this->defaultLocale;
$url = $this->router->generate($routeName, $routeParams);
$event->setResponse(new RedirectResponse($url));
}
}
}
public static function getSubscribedEvents()
{
return array(
// must be registered before the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}
And services.yml
services:
selly_webapp_landing.listeners.localeInParam_listener:
class: Selly\WebappLandingBundle\EventListener\LocaleInParamListener
arguments: [@router, "%kernel.default_locale%", "%locale_supported%"]
tags:
- { name: kernel.event_subscriber }
In parameters.yml you can specify supported locales:
locale_supported: ['en_US', 'pl_PL']