src/EventSubscriber/UserLocaleSubscriber.php line 25

Open in your IDE?
  1. <?php
  2. // src/EventSubscriber/UserLocaleSubscriber.php
  3. namespace App\EventSubscriber;
  4. use App\Entity\User;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  7. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  8. use Symfony\Component\Security\Http\SecurityEvents;
  9. /**
  10.  * Stores the locale of the user in the session after the
  11.  * login. This can be used by the LocaleSubscriber afterwards.
  12.  * @see https://symfony.com/doc/current/session/locale_sticky_session.html
  13.  */
  14. class UserLocaleSubscriber implements EventSubscriberInterface
  15. {
  16.     private $session;
  17.     public function __construct(SessionInterface $session)
  18.     {
  19.         $this->session $session;
  20.     }
  21.     public function onInteractiveLogin(InteractiveLoginEvent $event)
  22.     {
  23.         $user $event->getAuthenticationToken()->getUser();
  24.         if (!$user instanceof User) {
  25.             return;
  26.         }
  27.         if (null !== $user->getLocale()) {
  28.             $this->session->set('_locale'$user->getLocale());
  29.         }
  30.     }
  31.     public static function getSubscribedEvents()
  32.     {
  33.         return [
  34.             SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
  35.         ];
  36.     }
  37. }