<?php
namespace App\EventSubscriber;
use Artyum\RequestDtoMapperBundle\Exception\DtoMappingException;
use Artyum\RequestDtoMapperBundle\Exception\DtoValidationException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class DtoExceptionSubscriber implements EventSubscriberInterface
{
public function __construct(private UrlGeneratorInterface $urlGenerator)
{
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
$request = $event->getRequest();
/** @var FlashBagInterface $flashes */
$flashes = $event->getRequest()->getSession()->getBag('flashes');
if (!($exception instanceof DtoMappingException || $exception instanceof DtoValidationException)) {
return;
}
// handles website routes
$flashes->add('danger', 'La validation de la requête a échouée.');
if ($request->headers->get('referer') !== null) {
$redirectUrl = $request->headers->get('referer');
} else {
$redirectUrl = $this->urlGenerator->generate(
$request->attributes->get('_route'),
$request->attributes->get('_route_params')
);
}
$event->setResponse(new RedirectResponse($redirectUrl));
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => [
// set the priority higher than the Sentry subscriber (which is currently at 128)
['onKernelException', 130],
],
];
}
}