<?php
// src/EventSubscriber/ExceptionSubscriber.php
namespace App\EventSubscriber;
use App\Exception\ServiceException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class ExceptionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => [
['processException', 10],
['logException', 0],
['notifyException', -10],
],
];
}
public function processException(ExceptionEvent $event)
{
// ...
}
public function logException(ExceptionEvent $event)
{
// ...
}
public function notifyException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
if ($exception instanceof ServiceException) {
$session = new Session();
$session->getFlashBag()->add('notice', $exception->getMessage());
$referrerUrl = $this->getReferrer($event->getRequest()->getRequestUri());
if (!$referrerUrl) {
$referrerUrl = $event->getRequest()->getRequestUri();
}
$event->setResponse(new RedirectResponse($referrerUrl, 301));
}
return;
}
private function getReferrer(string $url): ?string
{
$parts = parse_url($url);
if (isset($parts['query'])) {
parse_str($parts['query'], $query);
if (isset($query['referrer'])) {
return $query['referrer'];
}
return null;
}
}
}