src/EventSubscriber/LocaleSubscriber.php line 42

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. class LocaleSubscriber implements EventSubscriberInterface
  7. {
  8.     public function __construct(
  9.         private string $defaultLocale 'lt'
  10.     ) {}
  11.     public static function getSubscribedEvents(): array
  12.     {
  13.         return [
  14.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  15.             KernelEvents::REQUEST => [['onKernelRequest'20]]
  16.         ];
  17.     }
  18.     public function onKernelRequest(RequestEvent $event): void
  19.     {
  20.         $request $event->getRequest();
  21. //        if (!$request->hasPreviousSession()) {
  22. //            // don't do anything if it's not the main request
  23. //            return;
  24. //        }
  25. //        if ($request->getContentType() === "json") {
  26. //            $locale = $request->getPreferredLanguage();
  27. //        } else {
  28.             $locale $request->get('_locale');
  29. //        }
  30.         if ($locale) {
  31.             $request->getSession()->set('_locale'$locale);
  32.             $request->setLocale($locale);
  33.         } else {
  34.             $sessionLocale $request->getSession()->get('_locale');
  35.             $request->setLocale($sessionLocale ?: $this->defaultLocale);
  36.         }
  37.     }
  38. }