<?php
// src/EventSubscriber/ExceptionSubscriber.php
// symfony v7.0
namespace App\EventSubscriber;
// For eventsubscriber
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
// Redirection
use Symfony\Component\HttpFoundation\RedirectResponse;
// Router - Get route by route name
// https://symfonycasts.com/screencast/symfony4-security/success-user-provider
use Symfony\Component\Routing\RouterInterface;
#[AsEventSubscriber(event: 'kernel.exception')]
class ExceptionSubscriber implements EventSubscriberInterface
{
// https://symfonycasts.com/screencast/symfony4-security/success-user-provider
private $router;
public function __construct( RouterInterface $router )
{
$this->router = $router;
}
public static function getSubscribedEvents() :array
{
// return the subscribed events, their methods and priorities
return [KernelEvents::EXCEPTION => [
['handleAllExceptions', 0]
]];
}
public function handleAllExceptions( ExceptionEvent $event )
{
$exception = $event->getThrowable();
switch ( get_class( $exception ) )
{
case 'Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException':
// -------------------------------------------------------------------
// AUTH ERROR
// -------------------------------------------------------------------
// User is not authenticated
// -------------------------------------------------------------------
// Redirect to login pages
// -------------------------------------------------------------------
$route = $this->router->generate('app_please_login'); // e.g. /auth
$event->setResponse(new RedirectResponse($route));
break;
default:
// Do nothing
}
}
} //eoClass ExceptionSubscriber
# [END error_reporting_setup_php_symfony]