From 2b20e23015b4b6a82ce6951179cd7308692f0134 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Rapha=C3=ABl=20Gertz?= Date: Wed, 14 Oct 2020 03:51:20 +0200 Subject: [PATCH] Add LocaleSubscriber to redirect used to logical language without session --- EventSubscriber/LocaleSubscriber.php | 60 ++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 EventSubscriber/LocaleSubscriber.php 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]] + ]; + } +} -- 2.41.1