src\EventListener\AccessDeniedListener.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\RedirectResponse;
  4. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  5. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  6. use Symfony\Component\Routing\RouterInterface;
  7. class AccessDeniedListener
  8. {
  9.     private $router;
  10.     public function __construct(RouterInterface $router)
  11.     {
  12.         $this->router $router;
  13.     }
  14.     public function __invoke(ExceptionEvent $event): void
  15.     {
  16.         $exception $event->getThrowable();
  17.         if (!$exception instanceof AccessDeniedHttpException) {
  18.             return;
  19.         }
  20.         // Redirect the user to a specific route
  21.         $url $this->router->generate('logout');
  22.         $response = new RedirectResponse($url);
  23.         $event->setResponse($response);
  24.     }
  25. }