src/EventListener/SimpleMessageExceptionSubscriber.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Exception\SimpleMessageException;
  4. use Psr\Container\ContainerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  12. use Symfony\Component\Routing\RouterInterface;
  13. class SimpleMessageExceptionSubscriber implements EventSubscriberInterface
  14. {
  15.     /**
  16.      * @var ContainerInterface
  17.      */
  18.     private $container;
  19.     /**
  20.      * @var UrlGeneratorInterface
  21.      */
  22.     private $urlGenerator;
  23.     
  24.     public function __construct(ContainerInterface $container)
  25.     {
  26.         $this->container $container;
  27.     }
  28.     
  29.     public static function getSubscribedEvents()
  30.     {
  31.         return array(
  32.             KernelEvents::EXCEPTION => 'onKernelException'
  33.         );
  34.     }
  35.     
  36.     public function onKernelException(ExceptionEvent $event)
  37.     {
  38.         $url $event->getRequest()->headers->get('referer');
  39.         $e $event->getThrowable();
  40.         if (!$e instanceof SimpleMessageException) {
  41.             return;
  42.         }
  43.         
  44.        $this->container->get('session')->getFlashBag()->add('error'$e->getMessage());
  45.        $event->setResponse(new RedirectResponse($url));
  46.        
  47.        return $event;
  48.     }
  49. }