<?php
namespace Harmonizely\Service\Locale\EventListener;
use Harmonizely\Core\Security\Contract\ISecurityHelper;
use Harmonizely\Model\EventTypeInterface;
use Harmonizely\Model\Organization;
use Harmonizely\Model\UserInterface;
use Harmonizely\Service\Locale\Event\SetLocaleEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\Translation\LocaleAwareInterface;
class SetLocaleListener implements EventSubscriberInterface
{
/**
* @var RequestStack
*/
private RequestStack $requestStack;
/**
* @var LocaleAwareInterface
*/
private LocaleAwareInterface $localeAware;
/**
* @var ISecurityHelper
*/
private ISecurityHelper $securityHelper;
/**
* @var string[]
*/
private $enabledLocales;
/**
* SetLocaleListener constructor.
*
* @param RequestStack $requestStack
* @param LocaleAwareInterface $localeAware
* @param ISecurityHelper $securityHelper
* @param string $enabledLocales
*/
public function __construct(
RequestStack $requestStack,
LocaleAwareInterface $localeAware,
ISecurityHelper $securityHelper,
string $enabledLocales
)
{
$this->requestStack = $requestStack;
$this->localeAware = $localeAware;
$this->securityHelper = $securityHelper;
$this->enabledLocales = explode('|', $enabledLocales . '|zh');
}
public static function getSubscribedEvents(): array
{
return [
SetLocaleEvent::NAME => ['onSetLocale'],
KernelEvents::REQUEST => ['onRequestSetLocale'],
];
}
/**
* @param RequestEvent $event
* @return void
*/
public function onRequestSetLocale(RequestEvent $event): void
{
$this->onSetLocale(new SetLocaleEvent(null, $this->securityHelper->getUser()));
}
/**
* @param SetLocaleEvent $event
*/
public function onSetLocale(SetLocaleEvent $event): void
{
$request = $this->requestStack->getCurrentRequest();
$locale = $request->getLocale();
$eventType = $event->getEventType();
$user = $event->getUser();
$organization = $event->getOrganization();
if ($eventType instanceof EventTypeInterface && !$eventType->isAutoLocale()) {
$locale = $eventType->getLocale();
} elseif ($user instanceof UserInterface && !$user->isAutoLocale()) {
$locale = $user->getLocale();
} elseif ($organization instanceof Organization && !$organization->isAutoLocale()) {
$locale = $organization->getLocale();
}
if ($locale) {
$locale = substr($locale, 0, 2);
if (!in_array($locale, $this->enabledLocales)) {
$locale = 'en';
}
$request->setLocale($locale);
$this->localeAware->setLocale($locale);
}
}
}