<?php
namespace App\Controller\System;
use Sylius\Bundle\ShopBundle\Locale\LocaleSwitcherInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Sylius\Component\Locale\Provider\LocaleProviderInterface;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
final class LocaleSwitchController
{
/** @var EngineInterface */
private $templatingEngine;
/** @var LocaleContextInterface */
private $localeContext;
/** @var LocaleProviderInterface */
private $localeProvider;
/** @var LocaleSwitcherInterface */
private $localeSwitcher;
public function __construct(
EngineInterface $templatingEngine,
LocaleContextInterface $localeContext,
LocaleProviderInterface $localeProvider,
LocaleSwitcherInterface $localeSwitcher
) {
$this->templatingEngine = $templatingEngine;
$this->localeContext = $localeContext;
$this->localeProvider = $localeProvider;
$this->localeSwitcher = $localeSwitcher;
}
public function renderAction(): Response
{
return $this->templatingEngine->renderResponse('@SyliusShop/Menu/_localeSwitch.html.twig', [
'active' => $this->localeContext->getLocaleCode(),
'locales' => $this->localeProvider->getAvailableLocalesCodes(),
]);
}
public function switchAction(Request $request, ?string $code = null): Response
{
$session = $request->getSession();
if (null === $code) {
if ($session->has('localeCode')) {
$code = $session->get('localeCode');
if ($code == 'en_US') {
$code = 'en';
} elseif ($code == 'ro_RO') {
$code = 'ro';
}
} else {
$code = $this->localeProvider->getDefaultLocaleCode();
}
}
if (!in_array($code, $this->localeProvider->getAvailableLocalesCodes(), true)) {
$code = 'ro';
}
$session->set('localeCode', $code);
return $this->localeSwitcher->handle($request, $code);
}
}