<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\RouterInterface;
class AccessDeniedListener
{
private $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function __invoke(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if (!$exception instanceof AccessDeniedHttpException) {
return;
}
// Redirect the user to a specific route
$url = $this->router->generate('logout');
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}