src/Shared/EventSubscriber/ExceptionSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Shared\EventSubscriber;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  9. use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;
  10. use Symfony\Component\Security\Core\Security;
  11. final class ExceptionSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(private UrlGeneratorInterface $urlGenerator, private RequestStack $requestStack)
  14.     {
  15.     }
  16.     /**
  17.      * @return array<string, string>
  18.      */
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [ExceptionEvent::class => 'onKernelException'];
  22.     }
  23.     public function onKernelException(ExceptionEvent $event): void
  24.     {
  25.         if (!$event->getThrowable()->getPrevious() instanceof InsufficientAuthenticationException) {
  26.             return; // @codeCoverageIgnore
  27.         }
  28.         $response = new RedirectResponse($this->urlGenerator->generate('security_login'));
  29.         $this->requestStack->getSession()->set(Security::AUTHENTICATION_ERROR$event->getThrowable()->getPrevious());
  30.         $event->setResponse($response);
  31.     }
  32. }