src/Subscriber/LocaleSubscriber.php line 56

Open in your IDE?
  1. <?php
  2. namespace App\Subscriber;
  3. use App\Entity\User;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  6. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  9. use Symfony\Component\Security\Http\SecurityEvents;
  10. /**
  11.  * Stores the locale of the user in the session after the
  12.  * login. This can be used by the LocaleSubscriber afterwards.
  13.  */
  14. class LocaleSubscriber implements EventSubscriberInterface
  15. {
  16.     /** @var SessionInterface $session */
  17.     protected $session;
  18.     /** @var string $defaultLocale */
  19.     protected $defaultLocale;
  20.     public function __construct(SessionInterface $session)
  21.     {
  22.         $this->session       $session;
  23.         $this->defaultLocale User::LOCALE_FR;
  24.     }
  25.     public function onKernelRequest(GetResponseEvent $event)
  26.     {
  27.         $request $event->getRequest();
  28.         // if on admin, locale is always en
  29.         $adminPath '/admin';
  30.         if (substr($request->getPathInfo(), 0strlen($adminPath)) == $adminPath) {
  31.             $request->setLocale(User::LOCALE_FR);
  32.             return;
  33.         }
  34.         if (!$request->hasPreviousSession()) {
  35.             return;
  36.         }
  37.         // try to see if the locale has been set as a _locale routing parameter
  38.         if ($locale $request->attributes->get('_locale')) {
  39.             $request->getSession()->set('_locale'$locale);
  40.         } else {
  41.             // if no explicit locale has been set on this request, use one from the session
  42.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  43.         }
  44.     }
  45.     public function onInteractiveLogin(InteractiveLoginEvent $event)
  46.     {
  47.         /** @var User $user */
  48.         $user $event->getAuthenticationToken()->getUser();
  49.         if (null !== $user->getUserData()->getInfoLocale()) {
  50.             $this->session->set('_locale'$user->getUserData()->getInfoLocale());
  51.         }
  52.     }
  53.     public static function getSubscribedEvents()
  54.     {
  55.         return [
  56.             SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
  57.             KernelEvents::REQUEST             => [['onKernelRequest'20]],
  58.         ];
  59.     }
  60. }