<?php
namespace App\Event;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use function str_starts_with;
/**
* EVENT SUBSCRIBER ONLY FOR request.host=hosts.boarding
*/
class SiteEventSubScriber implements EventSubscriberInterface {
/**
* @var ContainerBagInterface
*/
private $params;
const DEFAULT_LANGUAGE = 'fr';
const SUPPORTED_LANGUAGES = ['fr', 'en'];
public function __construct(ContainerBagInterface $params) {
$this->params = $params;
}
public static function getSubscribedEvents() {
return [
KernelEvents::REQUEST => ['onKernelRequest', 100],
];
}
public function onKernelRequest(RequestEvent $event) {
$r = $event->getRequest();
if($r->getHost() != $this->params->get('hosts.boarding')) return;
$this->autoSetLanguage($r);
}
/**
* Set language based on HTTP Accept-Language header
* @param Request $r
*/
protected function autoSetLanguage(Request $r) {
$r->setLocale(self::DEFAULT_LANGUAGE);
$acceptLanguage = $r->headers->get('Accept-Language');
if(!$acceptLanguage) return;
$languages = preg_split('/[;,]/', $acceptLanguage);
foreach($languages as $lang) {
if(str_starts_with($lang, 'q=')) continue;
$lang = preg_replace('/-.*$/', '', $lang);
if(in_array($lang, self::SUPPORTED_LANGUAGES)) {
$r->setLocale($lang);
return;
}
}
}
}