<?php
namespace App\EventSubscriber;
use App\Entity\Provider;
use App\Entity\Users;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Security;
class RedirectToLogoutSubscriber implements EventSubscriberInterface
{
public function __construct(private Security $security, private RouterInterface $router){}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest() ) {
return;
}
$user= $this->security->getUser();
if ($user instanceof Provider && !$user->getIsEnabled()) {
$event->setResponse(new RedirectResponse($this->router->generate('provider_logout')));
return;
}
if ($user instanceof Users && !$user->getIsEnabled()) {
$event->setResponse(new RedirectResponse($this->router->generate('logout')));
}
// if provider try to access to routes startwith /admin, redirect to provider home page
if ($user instanceof Provider && str_starts_with($event->getRequest()->getPathInfo(), '/admin')) {
$event->setResponse(new RedirectResponse($this->router->generate('home')));
}
}
}