<?php
declare(strict_types=1);
namespace App\Subscriber;
use App\Logger\Log;
use App\Service\IOptionService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\SecurityEvents;
class LocaleSubscriber implements EventSubscriberInterface
{
private Security $security;
/**
* @var Log
*/
protected $log;
public function __construct(
Log $log, Security $security)
{
$this->security = $security;
$this->log = $log;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 10],
];
}
public function onKernelRequest(RequestEvent $event)
{
if (!$event->getRequest()->isXmlHttpRequest()) {
try {
// reset the locale of the subrequest to the locale of the parent request
if (!empty($this->security->getUser()) && !empty($this->security->getUser()->getLang())) {
$lang = $this->security->getUser()->getLang();
} elseif (isset($_COOKIE[IOptionService::COOKIE_USER_PARAM]) && !empty($_COOKIE[IOptionService::COOKIE_USER_PARAM])) {
$decodeCookie = unserialize(base64_decode($_COOKIE[IOptionService::COOKIE_USER_PARAM]));
$lang = $decodeCookie->getLang();
} else {
$lang = IOptionService::DEFAULT_LOCAL;
}
$event->getRequest()->getSession()->set('_locale', \strtolower($lang));
$event->getRequest()->setLocale(\strtolower($lang));
} catch (\Exception $e) {}
}
}
}