src/EventListener/ExceptionListener.php line 22

Open in your IDE?
  1. <?php
  2. // src/EventListener/ExceptionListener.php
  3. namespace App\EventListener;
  4. use App\Entity\RedirectReponse;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. class ExceptionListener
  11. {
  12. private $em;
  13. public function __construct(EntityManagerInterface $em){
  14. $this->em = $em;
  15. }
  16. public function onKernelException(ExceptionEvent $event)
  17. {
  18. // You get the exception object from the received event
  19. $exception = $event->getThrowable();
  20. if(method_exists($exception,'getStatusCode') && in_array($exception->getStatusCode(),["404","500"]) ){
  21. $redirect = $this->em->getRepository(RedirectReponse::class)->findOneBy(['urlFrom'=>$event->getRequest()->getRequestUri()]);
  22. if ($redirect !== null)
  23. return $event->setResponse(new RedirectResponse($redirect->getUrlTo()));
  24. }
  25. }
  26. }