<?php
namespace App\Event\EventSubscriber;
use App\Api\BrcBackend\TranslationClient;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
class LocaleSubscriber implements EventSubscriberInterface
{
private CacheInterface $cache;
private TranslationClient $translationClient;
public function __construct(
CacheInterface $cache,
TranslationClient $translationClient
) {
$this->cache = $cache;
$this->translationClient = $translationClient;
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
$locale = $request->getLocale();
if (!$this->isLocaleEnabled($locale)) {
// $request->setLocale('pl');
// $request->attributes->set('_locale', 'pl');
throw new NotFoundHttpException('Locale not allowed.');
}
}
public function isLocaleEnabled(string $locale): bool
{
return $this->cache->get(
'is_locale_enabled_' . $locale,
function (ItemInterface $item) use ($locale) {
$item->expiresAfter(300);
$result = $this->translationClient->isEnabledLocale($locale);
if (isset($result['localeEnabled']) && $result['localeEnabled'] == true) {
return true;
}
return false;
});
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 20],
];
}
}