src/EventSubscriber/LocaleSubscriber.php line 18

Open in your IDE?
  1. <?php
  2. // src/EventSubscriber/LocaleSubscriber.php
  3. namespace App\EventSubscriber;
  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 'en')
  11.     {
  12.         $this->defaultLocale $defaultLocale;
  13.     }
  14.     public function onKernelRequest(RequestEvent $event)
  15.     {
  16.         $request $event->getRequest();
  17.         if (!$request->hasPreviousSession()) {
  18.             return;
  19.         }
  20.         // dd($request);
  21.         // try to see if the locale has been set as a _locale routing parameter
  22.         $locale $request->attributes->get('_locale');
  23.         if ($locale $request->attributes->get('_locale')) {
  24.             // dd($locale);
  25.             $request->getSession()->set('_locale'$locale);
  26.         } else {
  27.             // if no explicit locale has been set on this request, use one from the session
  28.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  29.         }
  30.         // dd($request);
  31.     }
  32.     public static function getSubscribedEvents()
  33.     {
  34.         return [
  35.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  36.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  37.         ];
  38.     }
  39. }