src/EventSubscriber/RedirectSubscriber.php line 24

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use Symfony\Component\Security\Core\Security;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  10. class RedirectSubscriber implements EventSubscriberInterface
  11. {
  12.     private Security $security;
  13.     private UrlGeneratorInterface $urlGenerator;
  14.     public function __construct(Security $securityUrlGeneratorInterface $urlGenerator)
  15.     {
  16.         $this->security $security;
  17.         $this->urlGenerator $urlGenerator;
  18.     }
  19.     public function onKernelRequest(RequestEvent $event): void
  20.     {
  21.         $path $event->getRequest()->getPathInfo();
  22.         $user $this->security->getUser();
  23.         if ($path == '/' && $user instanceof User && in_array('ROLE_CUSTOMER'$user->getRoles())) {
  24.             $response = new RedirectResponse($this->urlGenerator->generate('app_supply_customer'));
  25.             $event->setResponse($response);
  26.         }
  27.     }
  28.     public static function getSubscribedEvents(): array
  29.     {
  30.         return [
  31.             'kernel.request' => 'onKernelRequest',
  32.         ];
  33.     }
  34. }