<?php
namespace App\Listener;
use Doctrine\DBAL\Exception\InvalidFieldNameException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\RouterInterface;
class ExceptionListener implements EventSubscriberInterface
{
private RouterInterface $router;
private string $environment;
public function __construct( KernelInterface $kernel, RouterInterface $router )
{
$this->environment = $kernel->getEnvironment();
$this->router = $router;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
];
}
public function onKernelException( ExceptionEvent $event )
{
if ( $this->environment !== 'dev' ) {
return;
}
$exception = $event->getThrowable();
if ( $exception instanceof InvalidFieldNameException ) {
// Génère la route dev_update_bdd
$route = $this->router->generate( 'dev_update_bdd' );
// Redirige vers la route dev_update_bdd
$response = new RedirectResponse( $route );
$event->setResponse( $response );
}
}
}