<?php
namespace Atiweb\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class UserLocaleSubscriber implements EventSubscriberInterface
{
/**
* Locales autorisées
* @var array
*/
protected $allowedLanguages = [
'fr',
'es',
'it',
'de',
];
/**
* Locale par défaut
* @var string
*/
protected $defaultLocale = 'fr';
/**
* UserLocaleSubscriber constructor.
* @param string $defaultLocale
* @param string $allowedLanguagesPattern
*/
public function __construct(string $defaultLocale, array $allowedLanguagesPattern)
{
$this->defaultLocale = $defaultLocale;
$this->allowedLanguages = $allowedLanguagesPattern;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
/**
* Lorsque le user demande le changement de langue
*/
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $locale);
$request->setLocale($locale);
\Locale::setDefault($locale);
} else {
/**
* Si le user à une locale en session, sinon, on cherche via le navigateur
*/
if($request->getSession()->has('_locale')) {
$request->setLocale($request->getSession()->get('_locale'));
\Locale::setDefault($request->getSession()->get('_locale'));
} else {
if($locale = $this->findLocaleFromAcceptLanguage($request->headers->get("Accept-Language"))) {
$request->getSession()->set('_locale', $locale);
$request->setLocale($locale);
\Locale::setDefault($locale);
} else {
$request->getSession()->set('_locale', $this->defaultLocale);
$request->setLocale($this->defaultLocale);
\Locale::setDefault($this->defaultLocale);
}
}
}
}
protected function findLocaleFromAcceptLanguage($acceptLanguage)
{
$acceptLanguagesArray = preg_split('/,/', $acceptLanguage);
foreach ($acceptLanguagesArray as $acceptLanguage) {
foreach ($this->allowedLanguages as $allowedLanguage) {
if(preg_match('/^'.$allowedLanguage.'/', $acceptLanguage)) {
return $allowedLanguage;
}
}
}
return null;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => [
[ 'onKernelRequest', 18 ]
]
];
}
/**
* @return string
*/
public function getDefaultLocale(): string
{
return $this->defaultLocale;
}
}