src/Social/FrontendBundle/EventListener/TranslateListener.php line 60

Open in your IDE?
  1. <?php
  2. namespace Social\FrontendBundle\EventListener;
  3. use Social\InternalBundle\Entity\LanguageSetting;
  4. use Social\UserBundle\Entity\User;
  5. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\DependencyInjection\ContainerInterface;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  11. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  12. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  13. /**
  14.  * Class TranslateListener
  15.  *
  16.  * @package Social\FrontendBundle\EventListener
  17.  */
  18. class TranslateListener implements EventSubscriberInterface
  19. {
  20.     private $tokenStorage;
  21.     private $container;
  22.     private $defaultLanguage;
  23.     /**
  24.      * TranslateListener constructor.
  25.      *
  26.      * @param TokenStorageInterface  $tokenStorage
  27.      * @param ContainerInterface     $container
  28.      * @param string                 $defaultLanguage
  29.      */
  30.     public function __construct(
  31.         TokenStorageInterface $tokenStorage,
  32.         ContainerInterface $container,
  33.         string $defaultLanguage
  34.     ) {
  35.         $this->tokenStorage     $tokenStorage;
  36.         $this->container        $container;
  37.         $this->defaultLanguage  $defaultLanguage;
  38.     }
  39.     /**
  40.      * @return array
  41.      */
  42.     public static function getSubscribedEvents(): array
  43.     {
  44.         return [
  45.             KernelEvents::REQUEST => ['onKernelRequest'127],
  46.             KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest'0]],
  47.         ];
  48.     }
  49.     /**
  50.      * @param GetResponseEvent $event
  51.      *
  52.      * @return GetResponseEvent
  53.      */
  54.     public function onKernelRequest(GetResponseEvent $event): ?GetResponseEvent
  55.     {
  56.         $request $event->getRequest();
  57.         if ($request->get("_route") == "social_frontend_change_locale") {
  58.             return $event;
  59.         }
  60.         if (!$request->isXmlHttpRequest()) {
  61.             $languages $this->container->getParameter('languages');
  62.             $languages array_column($languages'code');
  63.             $tokenStorage $this->tokenStorage->getToken();
  64.             $locale $request->getSession()->get('_locale'$this->defaultLanguage);
  65.             // Check for user locale
  66.             if ($tokenStorage instanceof TokenInterface && $tokenStorage->getUser() instanceof User) {
  67.                 /** @var User $user */
  68.                 $user $this->tokenStorage->getToken()->getUser();
  69.                 if ($user) {
  70.                     if ($user->getLocale()) {
  71.                         $locale $user->getLocale();
  72.                     } elseif ($user->hasRole(User::ROLE_USER)) {
  73.                         $this->getConfiguredLanguage($request$languages,$locale);
  74.                     }
  75.                 }
  76.             } elseif ($request->get("_route") == "social_user_homepage") {
  77.                 $this->getConfiguredLanguage($request$languages$locale);
  78.             }
  79.             if (in_array($locale$languages)) {
  80.                 $this->handleLocale($event->getRequest(), $locale);
  81.             } else {
  82.                 $this->handleLocale($event->getRequest(), $this->defaultLanguage);
  83.             }
  84.             return $event;
  85.         }
  86.         return $event;
  87.     }
  88.     public function getConfiguredLanguage($request$languages, &$locale)
  89.     {
  90.         $em $this->container->get('doctrine.orm.entity_manager');
  91.         $isFromUserLanguageActive $em->getRepository(LanguageSetting::class)->findOneBy(['type' => LanguageSetting::TYPE_USER_BROWSER_LANGUAGE'active' => true]);
  92.         $isApiIpActive $em->getRepository(LanguageSetting::class)->findOneBy(['type' => LanguageSetting::TYPE_APIIP_LANGUAGE'active' => true]);
  93.         $isSetStaticLanguage $em->getRepository(LanguageSetting::class)->findOneBy(['type' => LanguageSetting::TYPE_STATIC_LANGUAGE'active' => true]);
  94.         if ($isFromUserLanguageActive) {
  95.             $localePreferences explode(",",$_SERVER['HTTP_ACCEPT_LANGUAGE']);
  96.             if(is_array($localePreferences) && count($localePreferences) > 0) {
  97.                 $browserLocale $localePreferences[0];
  98.                 $browserLocale explode("-"$browserLocale);
  99.                 $locale $browserLocale[0];
  100.             }
  101.         } else {
  102.             if ($isApiIpActive) {
  103.                 if ($isApiIpActive->getLanguage()) {
  104.                     $apiipData $this->container->get('social_internal.location_service')->execute($request->getClientIp());
  105.                     $configuredLanguages explode(", "$isApiIpActive->getLanguage());
  106.                     foreach ($configuredLanguages as $language) {
  107.                         if (array_key_exists($language$apiipData['languages']) && in_array($language$languages)) {
  108.                             $locale $language;
  109.                             break;
  110.                         }
  111.                     }
  112.                 } else {
  113.                     if (isset($apiipData['languages'])) {
  114.                         $locale array_key_first($apiipData['languages']);
  115.                     }
  116.                 }
  117.             } elseif ($isSetStaticLanguage) {
  118.                 $locale $isSetStaticLanguage->getLanguage();
  119.             }
  120.         }
  121.     }
  122.     /**
  123.      * @param FinishRequestEvent $event
  124.      * @return void
  125.      */
  126.     public function onKernelFinishRequest(FinishRequestEvent $event)
  127.     {
  128.         if (null === $parentRequest $this->container->get('request_stack')->getParentRequest()) {
  129.             return;
  130.         }
  131.         $this->handleLocale($parentRequest$parentRequest->getLocale());
  132.     }
  133.     /**
  134.      * @param Request $request 
  135.      * @param string $locale
  136.      * @return void
  137.      */
  138.     private function handleLocale(Request $requeststring $locale)
  139.     {
  140.         try {
  141.             $request->setLocale($locale);
  142.             $request->getSession()->set('_locale'$locale);
  143.             $this->container->get('translator')->setLocale($locale);
  144.             $this->container->get('translator')->setFallbackLocales([$locale]);
  145.         } catch (\Exception $e) {
  146.             $request->setLocale($this->defaultLanguage);
  147.             $request->getSession()->set('_locale'$this->defaultLanguage);
  148.             $this->container->get('translator')->setLocale($this->defaultLanguage);
  149.         }
  150.     }
  151. }