<?php
namespace App\EventListener;
use App\Exception\SimpleMessageException;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
class SimpleMessageExceptionSubscriber implements EventSubscriberInterface
{
/**
* @var ContainerInterface
*/
private $container;
/**
* @var UrlGeneratorInterface
*/
private $urlGenerator;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::EXCEPTION => 'onKernelException'
);
}
public function onKernelException(ExceptionEvent $event)
{
$url = $event->getRequest()->headers->get('referer');
$e = $event->getThrowable();
if (!$e instanceof SimpleMessageException) {
return;
}
$this->container->get('session')->getFlashBag()->add('error', $e->getMessage());
$event->setResponse(new RedirectResponse($url));
return $event;
}
}