src/EventListener/AccessDeniedListener.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Routing\RouterInterface;
  9. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  10. class AccessDeniedListener implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * @var RouterInterface
  14.      */
  15.     private RouterInterface $router;
  16.     public function __construct(RouterInterface $router)
  17.     {
  18.         $this->router $router;
  19.     }
  20.     public static function getSubscribedEvents(): array
  21.     {
  22.         return [
  23.             // the priority must be greater than the Security HTTP
  24.             // ExceptionListener, to make sure it's called before
  25.             // the default exception listener
  26.             KernelEvents::EXCEPTION => ['onKernelException'2],
  27.         ];
  28.     }
  29.     public function onKernelException(ExceptionEvent $event): void
  30.     {
  31.         $exception $event->getThrowable();
  32.         if (!$exception instanceof AccessDeniedException) {
  33.             return;
  34.         }
  35.         // ... perform some action (e.g. logging)
  36.         // optionally set the custom response
  37.         //$event->setResponse(new Response(null, 403));
  38.         $url $this->router->generate('app_login');
  39.         $response = new RedirectResponse($url);
  40.         $event->setResponse($response);
  41.         // or stop propagation (prevents the next exception listeners from being called)
  42.         //$event->stopPropagation();
  43.     }
  44. }