src/EventSubscriber/LocaleSubscriber.php line 29

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. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Symfony\Contracts\Translation\TranslatorInterface;
  8. class LocaleSubscriber implements EventSubscriberInterface
  9. {
  10.     private $defaultLocale;
  11.     private $translator;
  12.     public function __construct(string $defaultLocale 'en'TranslatorInterface $translator)
  13.     {
  14.         $this->defaultLocale $defaultLocale;
  15.         $this->translator $translator;
  16.     }
  17.     public function onKernelRequest(RequestEvent $event)
  18.     {
  19.         $request $event->getRequest();
  20.         if (!$request->hasPreviousSession()) {
  21.             return;
  22.         }
  23.         $locale $request->getSession()->get('_locale'$this->defaultLocale);
  24.         $request->setLocale($locale);
  25.         $this->translator->setLocale($locale);
  26.     }
  27.     public static function getSubscribedEvents()
  28.     {
  29.         return [
  30.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  31.         ];
  32.     }
  33. }