src/EventSubscriber/RedirectToLogoutSubscriber.php line 25

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Provider;
  4. use App\Entity\Users;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Routing\RouterInterface;
  10. use Symfony\Component\Security\Core\Security;
  11. class RedirectToLogoutSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(private Security $security, private RouterInterface $router){}
  14.     public static function getSubscribedEvents(): array
  15.     {
  16.         return [
  17.             KernelEvents::REQUEST => 'onKernelRequest',
  18.         ];
  19.     }
  20.     public function onKernelRequest(RequestEvent $event): void
  21.     {
  22.         if (!$event->isMainRequest() ) {
  23.             return;
  24.         }
  25.         $user$this->security->getUser();
  26.         if ($user instanceof Provider && !$user->getIsEnabled()) {
  27.             $event->setResponse(new RedirectResponse($this->router->generate('provider_logout')));
  28.             return;
  29.         }
  30.         if ($user instanceof Users && !$user->getIsEnabled()) {
  31.             $event->setResponse(new RedirectResponse($this->router->generate('logout')));
  32.         }
  33.         // if provider try to access to routes startwith /admin, redirect to provider home page
  34.         if ($user instanceof Provider && str_starts_with($event->getRequest()->getPathInfo(), '/admin')) {
  35.             $event->setResponse(new RedirectResponse($this->router->generate('home')));
  36.         }
  37.     }
  38. }