src/Subscriber/LocaleSubscriber.php line 49

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Subscriber;
  4. use App\Logger\Log;
  5. use App\Service\IOptionService;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Security\Core\Security;
  10. use Symfony\Component\Security\Http\SecurityEvents;
  11. class LocaleSubscriber implements EventSubscriberInterface
  12. {
  13.     private Security $security;
  14.     /**
  15.      * @var Log
  16.      */
  17.     protected $log;
  18.     public function __construct(
  19.         Log $logSecurity $security)
  20.     {
  21.         $this->security $security;
  22.         $this->log $log;
  23.     }
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [
  27.             KernelEvents::REQUEST => ['onKernelRequest'10],
  28.         ];
  29.     }
  30.     public function onKernelRequest(RequestEvent $event)
  31.     {
  32.         if (!$event->getRequest()->isXmlHttpRequest()) {
  33.             try {
  34.                 // reset the locale of the subrequest to the locale of the parent request
  35.                 if (!empty($this->security->getUser()) && !empty($this->security->getUser()->getLang())) {
  36.                     $lang $this->security->getUser()->getLang();
  37.                 } elseif (isset($_COOKIE[IOptionService::COOKIE_USER_PARAM]) && !empty($_COOKIE[IOptionService::COOKIE_USER_PARAM])) {
  38.                     $decodeCookie unserialize(base64_decode($_COOKIE[IOptionService::COOKIE_USER_PARAM]));
  39.                     $lang $decodeCookie->getLang();
  40.                 } else {
  41.                     $lang IOptionService::DEFAULT_LOCAL;
  42.                 }
  43.                 $event->getRequest()->getSession()->set('_locale'\strtolower($lang));
  44.                 $event->getRequest()->setLocale(\strtolower($lang));
  45.             } catch (\Exception $e) {}
  46.         }
  47.     }
  48. }