src/Service/EventListener/Redirect404Listener.php line 24

Open in your IDE?
  1. <?php
  2. namespace App\Service\EventListener;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  6. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  9. use Symfony\Component\Routing\Exception\NoConfigurationException;
  10. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  11. use Symfony\Component\Routing\RouterInterface;
  12. class Redirect404Listener implements EventSubscriberInterface
  13. {
  14.     private RouterInterface $router;
  15.     public function __construct(RouterInterface $router)
  16.     {
  17.         $this->router $router;
  18.     }
  19.     public function redirect(ExceptionEvent $event): void
  20.     {
  21.         $exception $event->getThrowable();
  22.         if (!$exception instanceof NotFoundHttpException) {
  23.             return;
  24.         }
  25.         $newRoute['_route'] = 'index';
  26.         // Redirect know old urls to /lv/old-url
  27.         if ($exception->getPrevious() instanceof ResourceNotFoundException) {
  28.             try {
  29.                 $newRoute $this->router->match(
  30.                     sprintf(
  31.                         '/%s%s',
  32.                         $event->getRequest()->getDefaultLocale(),
  33.                         $event->getRequest()->getRequestUri()
  34.                     )
  35.                 );
  36.             } catch (ResourceNotFoundException|NoConfigurationException|MethodNotAllowedException $notFoundException) {}
  37.         }
  38.         $response = new RedirectResponse($this->router->generate($newRoute['_route']));
  39.         $event->setResponse($response);
  40.     }
  41.     public static function getSubscribedEvents(): array
  42.     {
  43.         return [
  44.             KernelEvents::EXCEPTION => [
  45.                 'redirect',
  46.             ],
  47.         ];
  48.     }
  49. }