<?php
/*
* This file is part of the PEC Platform Bundle.
*
* (c) PEC project engineers & consultants
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pec\Bundle\PlatformBundle\Subscriber;
use Pec\Bundle\UserBundle\Entity\User;
use Pec\Bundle\PlatformBundle\Services\ILocaleService;
use Pec\Bundle\PlatformBundle\Services\IUserPreferenceService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class LocaleSubscriber implements EventSubscriberInterface {
/** @var IUserPreferenceService */
protected $userPreferenceService;
/** @var TokenStorageInterface */
protected $tokenStorage;
public function __construct(IUserPreferenceService $userPreferenceService, TokenStorageInterface $tokenStorage) {
$this->userPreferenceService = $userPreferenceService;
$this->tokenStorage = $tokenStorage;
}
public function onKernelRequest(RequestEvent $event): void {
if(!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
if(!$request->hasPreviousSession()) {
return;
}
$user = $this->getUser();
if($user !== null && $locale = $request->getLocale()) {
$this->userPreferenceService->setPreference($user, ILocaleService::PREFERENCE_KEY_LOCALE, $locale);
}
}
protected function getUser(): ?User {
$token = $this->tokenStorage->getToken();
$user = $token !== null ? $token->getUser() : null;
return $user instanceof User ? $user : null;
}
public static function getSubscribedEvents() {
return [
KernelEvents::REQUEST => [['onKernelRequest', 48]],
];
}
}