src/AppBundle/Security/RedirectUserIfAuthenticatedEventSubscriber.php line 26

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Security;
  3. use AppBundle\Entity\Customer;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\Routing\RouterInterface;
  6. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. /**
  10.  * Do some redirects on certain pages if user is logged in.
  11.  */
  12. class RedirectUserIfAuthenticatedEventSubscriber implements \Symfony\Component\EventDispatcher\EventSubscriberInterface
  13. {
  14.     private $tokenStorage;
  15.     private $router;
  16.     public function __construct(TokenStorageInterface $tRouterInterface $r)
  17.     {
  18.         $this->tokenStorage $t;
  19.         $this->router $r;
  20.     }
  21.     public function onKernelRequest(RequestEvent $event): void
  22.     {
  23.         if ($this->isUserLogged() && $event->isMainRequest()) {
  24.             $currentRoute $event->getRequest()->attributes->get('_route');
  25.             if ($this->isAuthenticatedUserOnAnonymousPage($currentRoute)) {
  26.                 $response = new RedirectResponse($this->router->generate('dashboard'));
  27.                 $event->setResponse($response);
  28.             }
  29.         }
  30.     }
  31.     private function isUserLogged(): bool
  32.     {
  33.         $user $this->tokenStorage?->getToken()?->getUser();
  34.         return $user instanceof Customer;
  35.     }
  36.     private function isAuthenticatedUserOnAnonymousPage(string $currentRoute): bool
  37.     {
  38.         return in_array(
  39.             $currentRoute,
  40.             ['login''reset''register''confirm']
  41.         );
  42.     }
  43.     public static function getSubscribedEvents(): array
  44.     {
  45.         return [KernelEvents::REQUEST => 'onKernelRequest'];
  46.     }
  47. }