<?php
namespace Harmonizely\EventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Translation\LocaleAwareInterface;
class RequestListener
{
/**
* @var LocaleAwareInterface
*/
private LocaleAwareInterface $locale;
/**
* @var string
*/
private string $defaultLocale;
/**
* @var array|false|string[]
*/
private array $enabledLocales;
/**
* @var RouterInterface
*/
private RouterInterface $router;
/**
* @var string
*/
private string $host;
/**
* RequestListener constructor.
* @param string $defaultLocale
* @param string $enabledLocales
* @param string $host
* @param LocaleAwareInterface $locale
* @param RouterInterface $router
*/
public function __construct(
string $defaultLocale,
string $enabledLocales,
string $host,
LocaleAwareInterface $locale,
RouterInterface $router
)
{
$this->locale = $locale;
$this->defaultLocale = $defaultLocale;
$this->enabledLocales = explode('|', $enabledLocales . '|zh');
$this->router = $router;
$this->host = $host;
}
/**
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->getRequest()->headers->has('X-Custom-Domain')) {
$this->router->getContext()->setHost($this->host);
}
$request = $event->getRequest();
$newLocale = $request->get('locale');
if (!$newLocale) {
$lang = $this->defaultLocale;
$languages = $request->getLanguages();
if (isset($languages[0])) {
if (in_array(substr($languages[0], 0, 2), $this->enabledLocales)) {
$lang = $languages[0];
}
}
$newLocale = substr($lang, 0, 2);
}
$request->setLocale($newLocale);
$this->locale->setLocale($newLocale);
}
}