src/EventListener/LocaleSubscriber.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Service\Language;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. class LocaleSubscriber implements EventSubscriberInterface
  8. {
  9.     private Language $language;
  10.     public function __construct(Language $language)
  11.     {
  12.         $this->language $language;
  13.     }
  14.     public function onKernelRequest(RequestEvent $event): void
  15.     {
  16.         $request $event->getRequest();
  17.         if (!$request->hasPreviousSession()) {
  18.             return;
  19.         }
  20.         if ($locale $request->attributes->get('_locale')) {
  21.             $request->getSession()->set('language'$locale);
  22.         } else {
  23.             $request->setLocale($this->language->getLanguage());
  24.         }
  25.     }
  26.     public static function getSubscribedEvents(): array
  27.     {
  28.         return [
  29.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  30.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  31.         ];
  32.     }
  33. }