src/EventSubscriber/ExceptionSubscriber.php line 33

Open in your IDE?
  1. <?php
  2. // src/EventSubscriber/ExceptionSubscriber.php
  3. namespace App\EventSubscriber;
  4. use App\Exception\ServiceException;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
  10. use Symfony\Component\HttpFoundation\Session\Session;
  11. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  12. class ExceptionSubscriber implements EventSubscriberInterface
  13. {
  14.     public static function getSubscribedEvents()
  15.     {
  16.         return [
  17.             KernelEvents::EXCEPTION => [
  18.                 ['processException'10],
  19.                 ['logException'0],
  20.                 ['notifyException', -10],
  21.             ],
  22.         ];
  23.     }
  24.     public function processException(ExceptionEvent $event)
  25.     {
  26.         // ...
  27.     }
  28.     public function logException(ExceptionEvent $event)
  29.     {
  30.         // ...
  31.     }
  32.     public function notifyException(ExceptionEvent $event)
  33.     {
  34.         $exception $event->getThrowable();
  35.         if ($exception instanceof ServiceException) {    
  36.             $session = new Session();
  37.             $session->getFlashBag()->add('notice'$exception->getMessage());
  38.             $referrerUrl $this->getReferrer($event->getRequest()->getRequestUri());
  39.             if (!$referrerUrl) {
  40.                 $referrerUrl $event->getRequest()->getRequestUri();
  41.             }
  42.         
  43.             $event->setResponse(new RedirectResponse($referrerUrl301));
  44.         }
  45.         return;
  46.     }
  47.     private function getReferrer(string $url): ?string
  48.     {
  49.         $parts parse_url($url);
  50.         if (isset($parts['query'])) {
  51.         parse_str($parts['query'], $query);
  52.             if (isset($query['referrer'])) {
  53.                 return $query['referrer'];
  54.             }
  55.             return null;
  56.         }
  57.     }
  58. }