<?php
declare(strict_types=1);
namespace App\Shared\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;
use Symfony\Component\Security\Core\Security;
final class ExceptionSubscriber implements EventSubscriberInterface
{
public function __construct(private UrlGeneratorInterface $urlGenerator, private RequestStack $requestStack)
{
}
/**
* @return array<string, string>
*/
public static function getSubscribedEvents(): array
{
return [ExceptionEvent::class => 'onKernelException'];
}
public function onKernelException(ExceptionEvent $event): void
{
if (!$event->getThrowable()->getPrevious() instanceof InsufficientAuthenticationException) {
return; // @codeCoverageIgnore
}
$response = new RedirectResponse($this->urlGenerator->generate('security_login'));
$this->requestStack->getSession()->set(Security::AUTHENTICATION_ERROR, $event->getThrowable()->getPrevious());
$event->setResponse($response);
}
}