<?php
namespace App\Package\Toolkit\Listener\LocaleListener;
// use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* LocaleListener
*
* Executed on KernelEvents::REQUEST
* - copies locale from route to session
* - if locale attribute does not exist in route then default locale is set in session
*
* @see include.yml
*
* @author Unknown
* @author Daniel Balowski <d.balowski@openform.pl> (_refactorer, _developer)
* @copyright Openform
* @since 03.2019
*/
class LocaleListener implements EventSubscriberInterface
{
/**
* @var string
*/
protected $frontDefaultLocale;
/**
* @var string
*/
protected $adminDefaultLocale;
/**
* @var string
*/
protected $adminSubdomain;
/**
* @param string $frontDefaultLocale
* @param string $adminDefaultLocale
* @param string $adminSubdomain
*/
public function __construct(string $frontDefaultLocale, string $adminDefaultLocale, string $adminSubdomain)
{
$this->frontDefaultLocale = $frontDefaultLocale;
$this->adminDefaultLocale = $adminDefaultLocale;
$this->adminSubdomain = $adminSubdomain;
}
/**
* Sets locale in session based on route
*
* @param RequestEvent $event
*
* @return void
*/
public function onKernelRequest(RequestEvent $event) : void
{
$request = $event->getRequest();
// Ommit webkit toolbar route
// (executed twice when does not ommit _wdt)
if (
! $request->attributes->get('_route') ||
$request->attributes->get('_route') == '_wdt'
) {
return;
}
$locale = $request->attributes->get('locale') ??
(
strpos($request->getHost(), $this->adminSubdomain) !== false ?
$this->adminDefaultLocale :
$this->frontDefaultLocale
);
$request->getSession()->set('locale', $locale);
$request->setLocale($locale);
return;
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents() : array
{
return [
KernelEvents::REQUEST => [
[
'onKernelRequest', 17
]
],
];
}
}