<?php
namespace App\Locale;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class LocaleSelector
{
public const SHOW_LOCALE_POPIN_SESSION_KEY = 'SHOW_LOCALE_POPIN_SESSION_KEY';
public const LOCALE_SELECT_URL_KEY = 'setUserLocale';
private $request;
public function __construct(
private readonly string $country,
RequestStack $requestStack,
private readonly RouterInterface $router,
private readonly array $allowedLocales,
private readonly array $proposedLocales,
private readonly TranslatorInterface $translator
) {
$this->request = $requestStack->getCurrentRequest();
}
public function setMustShowLanguagePopin(bool $show): void
{
if (!$this->request) {
return;
}
if (count($this->proposedLocales) > 2) {
return;
}
$this->request->getSession()->set(self::SHOW_LOCALE_POPIN_SESSION_KEY, $show);
}
public function shouldShowLanguagePopin(): bool
{
if (!$this->request || !$this->request->getSession() || count($this->proposedLocales) > 2) {
return false;
}
return (bool) $this->request->getSession()->get(self::SHOW_LOCALE_POPIN_SESSION_KEY);
}
public function pathToCurrentRouteInLocale($locale): string
{
if (!in_array($locale, $this->allowedLocales)) {
throw new \Exception(sprintf('This locale is not allowed in current configuration : %s. Allowed locales are : %s.', $locale, implode(', ', $this->allowedLocales)));
}
if (!$this->request) {
return '#';
}
$parameters = $this->request->get('_route_params');
$parameters['_locale'] = $locale;
$parameters[self::LOCALE_SELECT_URL_KEY] = 'true';
return $this->router->generate(
$this->request->get('_route'),
$parameters
);
}
public function getProposedLocales()
{
return $this->proposedLocales;
}
public function getProposedLocalesWithTranslatedNames()
{
$namesByLocale = [];
foreach ($this->proposedLocales as $localeForKey) {
$names = [];
foreach ($this->proposedLocales as $localeForTranslation) {
$names[] = $this->translator->trans(sprintf('frontend.locale.%s', $localeForKey), [], null, $localeForTranslation);
}
$namesByLocale[$localeForKey] = implode(' / ', $names);
}
return $namesByLocale;
}
}