<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class LocaleSubscriber implements EventSubscriberInterface
{
public function __construct(
private string $defaultLocale = 'lt'
) {}
public static function getSubscribedEvents(): array
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 20]]
];
}
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
// if (!$request->hasPreviousSession()) {
// // don't do anything if it's not the main request
// return;
// }
// if ($request->getContentType() === "json") {
// $locale = $request->getPreferredLanguage();
// } else {
$locale = $request->get('_locale');
// }
if ($locale) {
$request->getSession()->set('_locale', $locale);
$request->setLocale($locale);
} else {
$sessionLocale = $request->getSession()->get('_locale');
$request->setLocale($sessionLocale ?: $this->defaultLocale);
}
}
}