vendor/pec-platform/platform-bundle/Subscriber/LocaleSubscriber.php line 35

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the PEC Platform Bundle.
  4.  *
  5.  * (c) PEC project engineers &amp; consultants
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Pec\Bundle\PlatformBundle\Subscriber;
  11. use Pec\Bundle\UserBundle\Entity\User;
  12. use Pec\Bundle\PlatformBundle\Services\ILocaleService;
  13. use Pec\Bundle\PlatformBundle\Services\IUserPreferenceService;
  14. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  15. use Symfony\Component\HttpKernel\Event\RequestEvent;
  16. use Symfony\Component\HttpKernel\KernelEvents;
  17. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  18. class LocaleSubscriber implements EventSubscriberInterface {
  19.     /** @var IUserPreferenceService */
  20.     protected $userPreferenceService;
  21.     /** @var TokenStorageInterface */
  22.     protected $tokenStorage;
  23.     public function __construct(IUserPreferenceService $userPreferenceServiceTokenStorageInterface $tokenStorage) {
  24.         $this->userPreferenceService $userPreferenceService;
  25.         $this->tokenStorage $tokenStorage;
  26.     }
  27.     public function onKernelRequest(RequestEvent $event): void {
  28.         if(!$event->isMasterRequest()) {
  29.             return;
  30.         }
  31.         $request $event->getRequest();
  32.         if(!$request->hasPreviousSession()) {
  33.             return;
  34.         }
  35.         $user $this->getUser();
  36.         if($user !== null && $locale $request->getLocale()) {
  37.             $this->userPreferenceService->setPreference($userILocaleService::PREFERENCE_KEY_LOCALE$locale);
  38.         }
  39.     }
  40.     protected function getUser(): ?User {
  41.         $token $this->tokenStorage->getToken();
  42.         $user $token !== null $token->getUser() : null;
  43.         return $user instanceof User $user null;
  44.     }
  45.     public static function getSubscribedEvents() {
  46.         return [
  47.             KernelEvents::REQUEST => [['onKernelRequest'48]],
  48.         ];
  49.     }
  50. }