<?php
namespace App\EventSubscriber;
use InvalidArgumentException;
use Negotiation\LanguageNegotiator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\KernelInterface;
/**
* Class LocaleSubscriber
* @package App\EventSubscriber
*/
class LocaleSubscriber implements EventSubscriberInterface
{
/** @var array */
private $locales;
/** @var string */
private $defaultLocale;
/**
* LanguageListener constructor.
* @param $locales
* @param $defaultLocale
*/
public function __construct($locales, $defaultLocale)
{
$this->locales = explode('|', trim($locales));
if (empty($this->locales)) {
throw new InvalidArgumentException('The list of supported locales must not be empty.');
}
$this->defaultLocale = $defaultLocale ?: $this->locales[0];
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['redirectToLocalizedIndex', 100],
];
}
/**
* @param RequestEvent $event
*/
public function redirectToLocalizedIndex(RequestEvent $event)
{
// Do not modify sub-requests
if (KernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
// Assume all routes except the frontpage use the _locale parameter
if ($event->getRequest()->getPathInfo() !== '/' && $event->getRequest()->getPathInfo() !== '/calculator/redirect') {
return;
}
$language = $this->defaultLocale;
if (null !== $acceptLanguage = $event->getRequest()->headers->get('Accept-Language')) {
$negotiator = new LanguageNegotiator();
$best = $negotiator->getBest(
$event->getRequest()->headers->get('Accept-Language'),
$this->locales
);
if (null !== $best) {
$language = $best->getType();
}
if (!in_array($language, $this->locales)) {
$language = 'en';
}
}
if($event->getRequest()->getPathInfo() === '/calculator/redirect') {
$pathInfo = '/calculator';
}else {
$pathInfo = '/dashboard';
}
$response = new RedirectResponse('/' . $language . $pathInfo);
$event->setResponse($response);
}
}