src/EventSubscriber/LocaleSubscriber.php line 15

  1. <?php
  2. namespace App\EventSubscriber;
  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.     public function __construct(
  9.         private string $defaultLocale 'en'
  10.     ){}
  11.     public function onKernelRequest(RequestEvent $event)
  12.     {
  13.         $request $event->getRequest();
  14.         if (!$request->hasPreviousSession()) {
  15.             return;
  16.         }
  17.         // try to see if the locale has been set as a _locale routing parameter
  18.         if ($locale $request->attributes->get('_locale')) {
  19.             $request->getSession()->set('_locale'$locale);
  20.         } else {
  21.             // if no explicit locale has been set on this request, use one from the session
  22.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  23.         }
  24.     }
  25.     public static function getSubscribedEvents(): array
  26.     {
  27.         return [
  28.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  29.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  30.         ];
  31.     }
  32. }