<?php
// src/EventSubscriber/LocaleSubscriber.php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
class LocaleSubscriber implements EventSubscriberInterface
{
private string $defaultLocale;
private $twig;
public function __construct(Environment $twig, string $defaultLocale = 'fr')
{
$this->defaultLocale = $defaultLocale;
$this->twig = $twig;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $locale);
} else {
// if no explicit locale has been set on this request, use one from the session
$locale = $request->getSession()->get('_locale', $this->defaultLocale);
$request->setLocale($locale);
}
// setup Twig config for date and Timezone
$this->setTwigConfig ($locale);
}
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
public function setTwigConfig (string $locale) {
if ($locale == 'fr') {
$this->twig->getExtension(\Twig\Extension\CoreExtension::class)->setDateFormat('d/m/Y', '%d days');
$this->twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone('Europe/Paris');
}
}
}