<?php
namespace App\EventSubscriber;
use App\Service\LocaleService;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Routing\RouterInterface;
class Redirect404ToLocaleSubscriber
{
/**
* @var RouterInterface
*/
private $router;
/**
* @var LocaleService
*/
private $localeService;
/**
* @var RouterInterface $router
* @var LocaleService $localeService
*/
public function __construct(RouterInterface $router, LocaleService $localeService)
{
$this->router = $router;
$this->localeService = $localeService;
}
/**
* @var ExceptionEvent $event
* @return null
*/
public function onKernelException(ExceptionEvent $event)
{
// If not a HttpNotFoundException ignore
if (!$event->getThrowable() instanceof NotFoundHttpException) {
return;
}
$locale = substr($event->getRequest()->getRequestUri(), 1, 2);
if (in_array($locale, $this->localeService->getLocales())) {
// Create redirect response with url for the home page
$response = new RedirectResponse($this->router->generate('home', ['_locale' => $locale]));
}
else {
// Create redirect response with locale in url
$response = new RedirectResponse('/' . $event->getRequest()->getDefaultLocale() . $event->getRequest()->getRequestUri());
}
// Set the response to be processed
$event->setResponse($response);
}
}