src/EventSubscriber/UserLocaleSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  7. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  8. use Symfony\Component\Routing\RouterInterface;
  9. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  10. use Symfony\Component\Security\Http\SecurityEvents;
  11. /**
  12.  * Stores the locale of the user in the session after the
  13.  * login. This can be used by the LocaleSubscriber afterwards.
  14.  */
  15. class UserLocaleSubscriber implements EventSubscriberInterface
  16. {
  17.     private $session;
  18.     private $router;
  19.     public function __construct(SessionInterface $sessionRouterInterface $router)
  20.     {
  21.         $this->session $session;
  22.         $this->router $router;
  23.     }
  24.     public function onInteractiveLogin(InteractiveLoginEvent $event)
  25.     {
  26.         /** @var User $user */
  27.         $user $event->getAuthenticationToken()->getUser();
  28.         if (null !== $user->getLangue()) {
  29.             $this->session->set('language'$user->getLangue());
  30.             $event->getRequest()->attributes->set("_route_params", ["_locale" => $user->getLangue()]);
  31.             $response = new RedirectResponse($this->router->generate('app_homepage', ['_locale' => $user->getLangue(), UrlGeneratorInterface::ABSOLUTE_URL]));
  32.         } else {
  33.             $referer_url $event->getRequest()->headers->get('referer');
  34.             $response = new RedirectResponse($referer_url);
  35.         }
  36.         return $response;
  37.     }
  38.     public static function getSubscribedEvents()
  39.     {
  40.         return [
  41.             SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
  42.         ];
  43.     }
  44. }