<?php
namespace App\EventSubscriber\Api;
use App\Entity\Api\CoreModule\User;
use App\Helper\Api\JsonFormatter\Throwable\Formatter;
use App\Helper\Api\Translator\ApiTranslator;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
/**
* Subscriber to store locale from user options in session after user logged in.
*
* @package API
* @api
*/
class UserLocaleSubscriber extends AbstractSubscriber
{
/**
* Stack that controls the lifecycle of requests
*
* @var RequestStack
*/
protected RequestStack $requestStack;
/**
* 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 [
SecurityEvents::INTERACTIVE_LOGIN => [
['onInteractiveLogin', 0]
]
];
}
/**
* Constructor.
*
* @param Formatter $formatter
* @param ApiTranslator $translator
* @param RequestStack $requestStack
* @noinspection PhpPureAttributeCanBeAddedInspection
*/
public function __construct(Formatter $formatter, ApiTranslator $translator, RequestStack $requestStack)
{
parent::__construct($formatter, $translator);
$this->requestStack = $requestStack;
}
/**
* Store locale from user options in session after user logged in.
*
* @param InteractiveLoginEvent $event
* @return void
* @noinspection PhpUnused
*/
public function onInteractiveLogin(InteractiveLoginEvent $event): void
{
$token = $event->getAuthenticationToken();
/* @var UsernamePasswordToken $token */
// only handle for API routes and main firewall
if (preg_match('/^\/api\//', $event->getRequest()->getRequestUri()) &&
$token->getFirewallName() === 'main') {
$user = $token->getUser();
/* @var User $user */
$this->requestStack->getSession()->set('_locale', $user->getLocale());
}
}
}