src/Sylius/Bundle/ShopBundle/EventListener/NonChannelLocaleListener.php line 53

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Sylius package.
  4.  *
  5.  * (c) Paweł Jędrzejewski
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace Sylius\Bundle\ShopBundle\EventListener;
  12. use Sylius\Component\Locale\Provider\LocaleProviderInterface;
  13. use Symfony\Bundle\SecurityBundle\Security\FirewallConfig;
  14. use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
  15. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  16. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  17. use Webmozart\Assert\Assert;
  18. final class NonChannelLocaleListener
  19. {
  20.     /** @var LocaleProviderInterface */
  21.     private $channelBasedLocaleProvider;
  22.     /** @var FirewallMap */
  23.     private $firewallMap;
  24.     /** @var string[] */
  25.     private $firewallNames;
  26.     /**
  27.      * @param string[] $firewallNames
  28.      */
  29.     public function __construct(
  30.         LocaleProviderInterface $channelBasedLocaleProvider,
  31.         FirewallMap $firewallMap,
  32.         array $firewallNames
  33.     ) {
  34.         Assert::notEmpty($firewallNames);
  35.         Assert::allString($firewallNames);
  36.         $this->channelBasedLocaleProvider $channelBasedLocaleProvider;
  37.         $this->firewallMap $firewallMap;
  38.         $this->firewallNames $firewallNames;
  39.     }
  40.     /**
  41.      * @throws NotFoundHttpException
  42.      */
  43.     public function restrictRequestLocale(GetResponseEvent $event): void
  44.     {
  45.         if (!$event->isMasterRequest()) {
  46.             return;
  47.         }
  48.         $request $event->getRequest();
  49.         if ($request->attributes && in_array($request->attributes->get('_route'), ['_wdt''_profiler'])) {
  50.             return;
  51.         }
  52.         $currentFirewall $this->firewallMap->getFirewallConfig($request);
  53.         if (!$this->isFirewallSupported($currentFirewall)) {
  54.             return;
  55.         }
  56.         $requestLocale $request->getLocale();
  57.         if (!in_array($requestLocale$this->channelBasedLocaleProvider->getAvailableLocalesCodes(), true)) {
  58.             throw new NotFoundHttpException(
  59.                 sprintf('The "%s" locale is unavailable in this channel.'$requestLocale)
  60.             );
  61.         }
  62.     }
  63.     private function isFirewallSupported(?FirewallConfig $firewall null): bool
  64.     {
  65.         return
  66.             null !== $firewall &&
  67.             in_array($firewall->getName(), $this->firewallNames)
  68.         ;
  69.     }
  70. }