From: Raphaƫl Gertz Date: Wed, 14 Oct 2020 01:51:20 +0000 (+0200) Subject: Add LocaleSubscriber to redirect used to logical language without session X-Git-Tag: 0.1.1~14 X-Git-Url: https://git.rapsys.eu/airbundle/commitdiff_plain/2b20e23015b4b6a82ce6951179cd7308692f0134?ds=sidebyside Add LocaleSubscriber to redirect used to logical language without session --- diff --git a/EventSubscriber/LocaleSubscriber.php b/EventSubscriber/LocaleSubscriber.php new file mode 100644 index 0000000..7941a80 --- /dev/null +++ b/EventSubscriber/LocaleSubscriber.php @@ -0,0 +1,60 @@ +locales = $locales; + $this->router = $router; + } + + public function onKernelRequest(RequestEvent $event) { + //Retrieve request + $request = $event->getRequest(); + + //Check for session + //XXX: people blocking cookies will be stuck to preferred language version + if (!$request->hasPreviousSession()) { + //Get preferred language + //XXX: default language is unused, it will return locales[0] if everything fail + $preferred = $request->getPreferredLanguage($this->locales); + + //Check if preferred language differs from current request locale + if ($preferred != $request->getLocale()) { + //Save preferred locale in session + $request->getSession()->set('_locale', $preferred); + + //Generate current route with preferred language + //XXX: may trigger a Symfony\Component\Routing\Exception\RouteNotFoundException if route is not found for preferred locale + $uri = $this->router->generate( + //Current route + $request->get('_route'), + //Force preferred locale + ['_locale' => $preferred]+$request->get('_route_params') + ); + + //Regenerate route with preferred locale + $event->setResponse(new RedirectResponse($uri, 302)); + + //End process + return; + } + } + } + + public static function getSubscribedEvents() { + return [ + // must be registered before the default locale listener + KernelEvents::REQUEST => [['onKernelRequest', 10]] + ]; + } +}