<?php
namespace App\Security;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Twig\Environment;
class AccessDeniedHandler implements EventSubscriberInterface
{
/**
* @param Environment $environment
* @param RouterInterface $router
*/
public function __construct(
protected Environment $environment,
protected RouterInterface $router,
)
{
}
/**
* @return array[]
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => ['onKernelException', 2],
];
}
/**
* @param ExceptionEvent $event
* @return void
*/
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if (!$exception instanceof AccessDeniedException) {
return;
}
$event->setResponse(
new RedirectResponse($this->router->generate('admin_login'))
, Response::HTTP_FOUND
);
$event->stopPropagation();
}
}