src/Security/AccessDeniedHandler.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  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. use Twig\Environment;
  11. class AccessDeniedHandler implements EventSubscriberInterface
  12. {
  13.     /**
  14.      * @param Environment $environment
  15.      * @param RouterInterface $router
  16.      */
  17.     public function __construct(
  18.         protected Environment     $environment,
  19.         protected RouterInterface $router,
  20.     )
  21.     {
  22.     }
  23.     /**
  24.      * @return array[]
  25.      */
  26.     public static function getSubscribedEvents(): array
  27.     {
  28.         return [
  29.             KernelEvents::EXCEPTION => ['onKernelException'2],
  30.         ];
  31.     }
  32.     /**
  33.      * @param ExceptionEvent $event
  34.      * @return void
  35.      */
  36.     public function onKernelException(ExceptionEvent $event): void
  37.     {
  38.         $exception $event->getThrowable();
  39.         if (!$exception instanceof AccessDeniedException) {
  40.             return;
  41.         }
  42.         $event->setResponse(
  43.             new RedirectResponse($this->router->generate('admin_login'))
  44.             , Response::HTTP_FOUND
  45.         );
  46.         $event->stopPropagation();
  47.     }
  48. }