<?php
// src/EventListener/ExceptionListener.php
namespace App\EventListener;
use App\Entity\RedirectReponse;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
class ExceptionListener
{
private $em;
public function __construct(EntityManagerInterface $em){
$this->em = $em;
}
public function onKernelException(ExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getThrowable();
if(method_exists($exception,'getStatusCode') && in_array($exception->getStatusCode(),["404","500"]) ){
$redirect = $this->em->getRepository(RedirectReponse::class)->findOneBy(['urlFrom'=>$event->getRequest()->getRequestUri()]);
if ($redirect !== null)
return $event->setResponse(new RedirectResponse($redirect->getUrlTo()));
}
}
}