src/EventSubscriber/LocaleSubscriber.php line 18

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace PPAdmin\EventSubscriber;
  3. use JetBrains\PhpStorm\ArrayShape;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. /**
  9.  * Allows overriding UI language by manual language switch
  10.  * @link https://symfony.com/doc/current/session/locale_sticky_session.html
  11.  */
  12. class LocaleSubscriber implements EventSubscriberInterface
  13. {
  14.     const LOCALE_KEY '_locale';
  15.     public function onKernelRequest(RequestEvent $event)
  16.     {
  17.         $request $event->getRequest();
  18.         if (
  19.             !$request->hasPreviousSession() ||
  20.             !$event->isMainRequest()
  21.         ) {
  22.             return;
  23.         }
  24.         $session $request->getSession();
  25.         if ($locale $request->get(self::LOCALE_KEY)) {
  26.             $session->set(self::LOCALE_KEY$locale);
  27.             $response = new RedirectResponse($request->getPathInfo());
  28.             $event->setResponse($response);
  29.             return;
  30.         }
  31.         $locale $session->get(self::LOCALE_KEY);
  32.         if($locale){
  33.             $request->setLocale($locale);
  34.         }
  35.     }
  36.     #[ArrayShape([KernelEvents::REQUEST => "array[]"])]
  37.     public static function getSubscribedEvents(): array
  38.     {
  39.         return [
  40.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  41.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  42.         ];
  43.     }
  44. }