<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use Locale;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class LocaleSetterEventSubscriber implements EventSubscriberInterface
{
private const QUERY_PARAMETER_LOCALE = 'lang';
private const LOCALE_LIST = [
'en',
'hu'
];
public const SESSION_PARAM_LOCALE = 'locale';
private string $defaultLocale;
public function __construct(string $defaultLocale)
{
$this->defaultLocale = $defaultLocale;
}
public static function getSubscribedEvents(): array
{
return [
// InteractiveLoginEvent::class => 'onInteractiveLogin',
RequestEvent::class => [['onRequest', 32]],
// WorkerStartedEvent::class => 'onWorkerStarted',
ConsoleEvents::COMMAND => 'onCommand'
];
}
// public function onInteractiveLogin(InteractiveLoginEvent $event): void
// {
// $user = $event->getAuthenticationToken()->getUser();
//
// if (isset($user)) {
// $event->getRequest()->getSession()->set(self::SESSION_PARAM_LOCALE, $user->getLocale());
// }
// }
public function onRequest(RequestEvent $event): void
{
$request = $event->getRequest();
$locale = $this->getLocaleForRequest($request);
$request->setLocale($locale);
$request->getSession()->set(self::SESSION_PARAM_LOCALE, $locale);
Locale::setDefault($locale);
}
// public function onWorkerStarted(WorkerStartedEvent $event): void
// {
// Locale::setDefault($this->defaultLocale);
// }
public function onCommand(ConsoleCommandEvent $event): void
{
Locale::setDefault($this->defaultLocale);
}
private function getLocaleForRequest(Request $request): string
{
if (
$request->query->has(self::QUERY_PARAMETER_LOCALE) &&
in_array(
$request->query->get(self::QUERY_PARAMETER_LOCALE),
self::LOCALE_LIST,
true
)
) {
return $request->query->get(self::QUERY_PARAMETER_LOCALE);
}
if ($request->getSession()->has(self::SESSION_PARAM_LOCALE)) {
return $request->getSession()->get(self::SESSION_PARAM_LOCALE);
}
return $this->defaultLocale;
}
}