src/EventSubscriber/DtoExceptionSubscriber.php line 25

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Artyum\RequestDtoMapperBundle\Exception\DtoMappingException;
  4. use Artyum\RequestDtoMapperBundle\Exception\DtoValidationException;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  11. class DtoExceptionSubscriber implements EventSubscriberInterface
  12. {
  13. public function __construct(private UrlGeneratorInterface $urlGenerator)
  14. {
  15. }
  16. public function onKernelException(ExceptionEvent $event): void
  17. {
  18. $exception = $event->getThrowable();
  19. $request = $event->getRequest();
  20. /** @var FlashBagInterface $flashes */
  21. $flashes = $event->getRequest()->getSession()->getBag('flashes');
  22. if (!($exception instanceof DtoMappingException || $exception instanceof DtoValidationException)) {
  23. return;
  24. }
  25. // handles website routes
  26. $flashes->add('danger', 'La validation de la requête a échouée.');
  27. if ($request->headers->get('referer') !== null) {
  28. $redirectUrl = $request->headers->get('referer');
  29. } else {
  30. $redirectUrl = $this->urlGenerator->generate(
  31. $request->attributes->get('_route'),
  32. $request->attributes->get('_route_params')
  33. );
  34. }
  35. $event->setResponse(new RedirectResponse($redirectUrl));
  36. }
  37. public static function getSubscribedEvents(): array
  38. {
  39. return [
  40. KernelEvents::EXCEPTION => [
  41. // set the priority higher than the Sentry subscriber (which is currently at 128)
  42. ['onKernelException', 130],
  43. ],
  44. ];
  45. }
  46. }