src/Core/EventSubscriber/Language/LocaleSubscriber.php line 17

Open in your IDE?
  1. <?php
  2. namespace App\Core\EventSubscriber\Language;
  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 'fr')
  9.     {
  10.     }
  11.     public function onKernelRequest(RequestEvent $event): void
  12.     {
  13.         $request $event->getRequest();
  14.         if (!$request->hasPreviousSession()) {
  15.             return;
  16.         }
  17.         if ($locale $request->attributes->get('_locale')) {
  18.             $request->getSession()->set('_locale'$locale);
  19.         } else {
  20.             /** @var string $loc */
  21.             $loc $request->getSession()->get('_locale'$this->defaultLocale);
  22.             $request->setLocale($loc);
  23.         }
  24.     }
  25.     public static function getSubscribedEvents(): array
  26.     {
  27.         return [
  28.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  29.         ];
  30.     }
  31. }