src/Sylius/Bundle/ShopBundle/Controller/LocaleSwitchController.php line 58

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\Controller;
  12. use Sylius\Bundle\ShopBundle\Locale\LocaleSwitcherInterface;
  13. use Sylius\Component\Locale\Context\LocaleContextInterface;
  14. use Sylius\Component\Locale\Provider\LocaleProviderInterface;
  15. use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\HttpKernel\Exception\HttpException;
  19. final class LocaleSwitchController
  20. {
  21.     /** @var EngineInterface */
  22.     private $templatingEngine;
  23.     /** @var LocaleContextInterface */
  24.     private $localeContext;
  25.     /** @var LocaleProviderInterface */
  26.     private $localeProvider;
  27.     /** @var LocaleSwitcherInterface */
  28.     private $localeSwitcher;
  29.     public function __construct(
  30.         EngineInterface $templatingEngine,
  31.         LocaleContextInterface $localeContext,
  32.         LocaleProviderInterface $localeProvider,
  33.         LocaleSwitcherInterface $localeSwitcher
  34.     ) {
  35.         $this->templatingEngine $templatingEngine;
  36.         $this->localeContext $localeContext;
  37.         $this->localeProvider $localeProvider;
  38.         $this->localeSwitcher $localeSwitcher;
  39.     }
  40.     public function renderAction(): Response
  41.     {
  42.         return $this->templatingEngine->renderResponse('@SyliusShop/Menu/_localeSwitch.html.twig', [
  43.             'active' => $this->localeContext->getLocaleCode(),
  44.             'locales' => $this->localeProvider->getAvailableLocalesCodes(),
  45.         ]);
  46.     }
  47.     public function switchAction(Request $request, ?string $code null): Response
  48.     {
  49.         if (null === $code) {
  50.             $code $this->localeProvider->getDefaultLocaleCode();
  51.         }
  52.         if (!in_array($code$this->localeProvider->getAvailableLocalesCodes(), true)) {
  53.             throw new HttpException(
  54.                 Response::HTTP_NOT_ACCEPTABLE,
  55.                 sprintf('The locale code "%s" is invalid.'$code)
  56.             );
  57.         }
  58.         return $this->localeSwitcher->handle($request$code);
  59.     }
  60. }