<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class LocaleSetter implements EventSubscriberInterface
{
private const COOKIES_LOCALE_KEY = '_lang';
private const AVAILABLE_LOCALES = ['en','ru','ua'];
public static function getSubscribedEvents(): array
{
// return the subscribed events, their methods and priorities
return [
KernelEvents::REQUEST => [
['onKernelRequest', 20],
],
KernelEvents::RESPONSE => [
['onKernelResponse', 20],
]
];
}
private $defaultLocale;
public function __construct(string $defaultLocale = 'en')
{
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$browser_pref = $request->getPreferredLanguage(self::AVAILABLE_LOCALES);
$this->defaultLocale = $request->cookies->get(self::COOKIES_LOCALE_KEY,$browser_pref);
$request_locale = $request->getSession()->get(self::COOKIES_LOCALE_KEY, $this->defaultLocale);
if ($locale = $request->attributes->get('_locale')) {
$request_locale = $locale;
}
if (!in_array($request_locale , self::AVAILABLE_LOCALES)){
$request_locale = self::AVAILABLE_LOCALES[0];
}
$request->getSession()->set(self::COOKIES_LOCALE_KEY,$request_locale);
$request->setLocale($request_locale);
}
public function onKernelResponse(ResponseEvent $event){
$request = $event->getRequest();
$response = $event->getResponse();
$current_locale = $request->getLocale();
$current_cookie = $request->cookies->get(self::COOKIES_LOCALE_KEY, '');
if ($current_cookie !== $current_locale){
$response->headers->setCookie(new Cookie(self::COOKIES_LOCALE_KEY, $current_locale));
}
}
}