src/EventListener/LocaleSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. class LocaleSubscriber implements EventSubscriberInterface
  7. {
  8.     private $defaultLocale;
  9.     public function __construct(string $defaultLocale 'en_GB')
  10.     {
  11.         $this->defaultLocale $defaultLocale;
  12.     }
  13.     public function onKernelRequest(RequestEvent $event): void
  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.         if ($locale $request->attributes->get('_locale')) {
  21.             $request->getSession()->set('_locale'$locale);
  22.         // If no explicit locale has been set on thie request, use one from the
  23.         // session.
  24.         } else {
  25.             $request->setLocale(
  26.                 $request->getSession()->get('_locale'$this->defaultLocale)
  27.             );
  28.         }
  29.     }
  30.     public static function getSubscribedEvents(): array
  31.     {
  32.         return [
  33.             KernelEvents::REQUEST => [['onKernelRequest'20]]
  34.         ];
  35.     }
  36. }