src/EventSubscriber/LocaleEventSubscriber.php line 14

Open in your IDE?
  1. <?php
  2. namespace EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. class LocaleEventSubscriber implements EventSubscriberInterface
  8. {
  9.     protected string $defaultLocale 'en';
  10.     public function onKernelRequest(RequestEvent $event)
  11.     {
  12.         $request $event->getRequest();
  13.         if (!$request->hasPreviousSession()) {
  14.             return;
  15.         }
  16.         // if we're in a custom signup change the lang based on the lang query param
  17.         if ($request->getPathInfo() == '/registration/' && $request->query->has('lang')) {
  18.             $request->getSession()->set('_locale'$request->query->get('lang'));
  19.         }
  20.         // try to see if the locale has been set as a _locale routing parameter
  21.         if ($locale $request->attributes->get('_locale')) {
  22.             $request->getSession()->set('_locale'$locale);
  23.         } else {
  24.             // if no explicit locale has been set on this request, use one from the session
  25.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  26.         }
  27.     }
  28.     public static function getSubscribedEvents(): array
  29.     {
  30.         return [
  31.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  32.         ];
  33.     }
  34. }