src/EventSubscriber/Redirect404ToLocaleSubscriber.php line 39

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Service\LocaleService;
  4. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  5. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  9. use Symfony\Component\Routing\RouterInterface;
  10. class Redirect404ToLocaleSubscriber
  11. {
  12.     /**
  13.      * @var RouterInterface
  14.      */
  15.     private $router;
  16.     /**
  17.      * @var LocaleService
  18.      */
  19.     private $localeService;
  20.     /**
  21.      * @var RouterInterface $router
  22.      * @var LocaleService $localeService
  23.      */
  24.     public function __construct(RouterInterface $routerLocaleService $localeService)
  25.     {
  26.         $this->router $router;
  27.         $this->localeService $localeService;
  28.     }
  29.     /**
  30.      * @var ExceptionEvent $event
  31.      * @return null
  32.      */
  33.     public function onKernelException(ExceptionEvent $event)
  34.     {
  35.         // If not a HttpNotFoundException ignore
  36.         if (!$event->getThrowable() instanceof NotFoundHttpException) {
  37.             return;
  38.         }
  39.         $locale substr($event->getRequest()->getRequestUri(), 12);
  40.         if (in_array($locale$this->localeService->getLocales())) {
  41.             // Create redirect response with url for the home page
  42.             $response = new RedirectResponse($this->router->generate('home', ['_locale' => $locale]));
  43.         }
  44.         else {
  45.             // Create redirect response with locale in url
  46.             $response = new RedirectResponse('/' $event->getRequest()->getDefaultLocale() . $event->getRequest()->getRequestUri());
  47.         }
  48.         // Set the response to be processed
  49.         $event->setResponse($response);
  50.     }
  51. }