src/EventListener/RequestListener.php line 27
<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class RequestListener
{
private RequestStack $requestStack;
/**
* @param RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
/**
* Redirect / to /de or /en or do nothing.
*
* @param RequestEvent $event
* @return void
*/
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
$uri = $request->getRequestUri();
// Automatically redirect ONLY for start page, means "/"
$redirectUris = [
'/',
];
if (!in_array($uri, $redirectUris, true)) {
// Do nothing if it is not start page "/"
// Let Sulu do the job (show 404 or redirect internally)
return;
}
$supportedLocales = [
'de', # Default
'en', # Secondary
];
// Locale from browser - preferred language/locale --> "fr", "fr_FR", "vi", "en_US", ...
$localeFromBrowser = $this->requestStack->getCurrentRequest()->getPreferredLanguage();
if (!empty($localeFromBrowser) && strlen($localeFromBrowser) >= 2) {
$localeFromBrowser = substr($localeFromBrowser, 0, 2);
// Redirect to /de or /en
if (in_array($localeFromBrowser, $supportedLocales, true)) {
$event->setResponse(new RedirectResponse('/' . $localeFromBrowser, 301));
}
}
// Otherwise let Sulu redirect internally to /de because de is default!
}
}