src/AppBundle/EventListener/LocaleSubscriber.php line 18

Open in your IDE?
  1. <?php
  2. namespace AppBundle\EventListener;
  3. use Symfony\Component\HttpKernel\Event\RequestEvent;
  4. use Symfony\Component\HttpKernel\KernelEvents;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. class LocaleSubscriber implements EventSubscriberInterface
  7. {
  8.     private string $defaultLocale;
  9.     public function __construct(string $defaultLocale 'en')
  10.     {
  11.         $this->defaultLocale $defaultLocale;
  12.     }
  13.     public function onKernelRequest(RequestEvent $event)
  14.     {
  15.         $request $event->getRequest();
  16.         if (!$request->hasPreviousSession()) {
  17.             return;
  18.         }
  19.         // try to see if the locale has been set as a _locale routing parameter
  20.         $locale $request->attributes->get('_locale');
  21.         if ($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()
  29.     {
  30.         return [
  31.             // must be registered after the default Locale listener
  32.             KernelEvents::REQUEST => [['onKernelRequest'15]],
  33.         ];
  34.     }
  35. }