src/Core/EventSubscriber/LocaleSubscriber.php line 39

  1. <?php
  2. namespace App\Core\EventSubscriber;
  3. use JetBrains\PhpStorm\ArrayShape;
  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 $defaultLocale;
  10.     public function __construct(string $defaultLocale)
  11.     {
  12.         $this->defaultLocale $defaultLocale;
  13.     }
  14.     #[ArrayShape([KernelEvents::REQUEST => 'array[]'])]
  15.     public static function getSubscribedEvents(): array
  16.     {
  17.         return [
  18.             KernelEvents::REQUEST => [
  19.                 ['onKernelRequest'20],
  20.             ],
  21.         ];
  22.     }
  23.     public function onKernelRequest(RequestEvent $event)
  24.     {
  25.         $request $event->getRequest();
  26.         if (!$request->hasPreviousSession()) {
  27.             return;
  28.         }
  29.         if ($locale $request->attributes->get('_locale')) {
  30.             $request->getSession()->set('_locale'$locale);
  31.         } else {
  32.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  33.         }
  34.     }
  35. }