src/EventSubscriber/LocaleSubscriber.php line 13

Open in your IDE?
  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(private string $defaultLocale){}
  9.     public function onKernelRequest(RequestEvent $event): void
  10.     {
  11.         $request $event->getRequest();
  12.         if (!$request->hasPreviousSession()) {
  13.             return;
  14.         }
  15.         // try to see if the locale has been set as a _locale routing parameter
  16.         if ($locale $request->get('_locale')) {
  17.             $request->getSession()->set('_locale'$locale);
  18.         }
  19.         $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  20.     }
  21.     public static function getSubscribedEvents(): array
  22.     {
  23.         return [
  24.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  25.         ];
  26.     }
  27. }