src/EventSubscriber/UserLocaleSubscriber.php line 28

Open in your IDE?
  1. <?php
  2. // src/EventSubscriber/UserLocaleSubscriber.php
  3. namespace App\EventSubscriber;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  7. use Symfony\Component\Security\Http\SecurityEvents;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. /**
  10.  * Stores the locale of the user in the session after the
  11.  * login. This can be used by the LocaleSubscriber afterwards.
  12.  */
  13. class UserLocaleSubscriber implements EventSubscriberInterface
  14. {
  15.     private $requestStack;
  16.     public function __construct(RequestStack $requestStackEntityManagerInterface $em)
  17.     {
  18.         $this->requestStack $requestStack;
  19.         $this->em $em;
  20.     }
  21.     public function onInteractiveLogin(InteractiveLoginEvent $event)
  22.     {
  23.         $user $event->getAuthenticationToken()->getUser();
  24.         
  25.         $user->setLastLogin(new \DateTime());
  26.         $this->em->persist($user);
  27.         $this->em->flush();
  28.         
  29.         if (null !== $user->getLocale()) {           
  30.             $this->requestStack->getSession()->set('_locale'$user->getLocale());
  31.         }
  32.              
  33.     }
  34.    
  35.     public static function getSubscribedEvents()
  36.     {
  37.         return [
  38.             SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
  39.         ];
  40.     }
  41. }