<?php
namespace App\EventSubscriber\Api;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Subscriber to set locale to session from explicit routing parameter or restore locale from previous session.
*
* @package API
* @internal
*/
class LocaleSubscriber extends AbstractSubscriber
{
/**
* Key for locale configuration in Symfony session.
*/
const SYMFONY_SESSION_LOCALE_KEY = '_locale';
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * ['eventName' => 'methodName']
* * ['eventName' => ['methodName', $priority]]
* * ['eventName' => [['methodName1', $priority], ['methodName2']]]
*
* The code must not depend on runtime state as it will only be called at compile time.
* All logic depending on runtime state must be put into the individual methods handling the events.
*
* @noinspection PhpArrayShapeAttributeCanBeAddedInspection
* @noinspection PhpUnused
*/
public static function getSubscribedEvents(): array
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener (currently 16 by
// bin/console debug:event)
KernelEvents::REQUEST => [
['onKernelRequest', 20]
]
];
}
/**
* Set locale to session from explicit routing parameter or restore locale from previous session.
*
* @param RequestEvent $event
* @return void
* @noinspection PhpUnused
*/
public function onKernelRequest(RequestEvent $event): void
{
/** only handle API routes and ignore the login route (handled by @link UserLocaleSubscriber) */
if (preg_match('/^\/api\//', $event->getRequest()->getRequestUri()) &&
preg_match('/^\/api\/[a-z]{2}\/login$/', $event->getRequest()->getRequestUri()) != 1) {
$request = $event->getRequest();
// be more efficient
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
if ($locale = $request->attributes->get(static::SYMFONY_SESSION_LOCALE_KEY)) {
// store explicit routing parameter in the session
$request->getSession()->set(static::SYMFONY_SESSION_LOCALE_KEY, $locale);
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale(
$request->getSession()->get(
static::SYMFONY_SESSION_LOCALE_KEY,
$_ENV['MANDATORY_TRANSLATION_LOCALE']
)
);
}
}
}
}