<?php/** * Class LocaleSubscriber * @package MWS\IntlBundle\EventSubscriber * @author Martin Walther <martin@myweb.solutions> * * (c) MyWebSolutions */namespace MWS\IntlBundle\EventSubscriber;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\HttpKernel\Event\RequestEvent;use Symfony\Component\HttpKernel\Event\ResponseEvent;use Symfony\Component\HttpKernel\KernelEvents;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\Validator\Constraints\Locale;use Symfony\Component\Validator\Validator\ValidatorInterface;class LocaleSubscriber implements EventSubscriberInterface{ /** * @var string */ private string $defaultLocale; /** * @var array */ private array $supportedLocales; /** * @var ValidatorInterface */ private ValidatorInterface $validator; /** * @var string */ protected string $currentLocale; /** * LocaleSubscriber constructor. * @param string $defaultLocale * @param array $supportedLocales * @param ValidatorInterface $validator */ public function __construct(ValidatorInterface $validator, array $supportedLocales, string $defaultLocale = 'en_US') { $this->defaultLocale = $defaultLocale; $this->supportedLocales = $supportedLocales; $this->validator = $validator; } /** * @return array */ public static function getSubscribedEvents(): array { return array( // must be registered after the default Locale listener KernelEvents::REQUEST => [['onKernelRequest', 17]], KernelEvents::RESPONSE =>['setContentLanguage'] ); } /** * @param RequestEvent $event */ public function onKernelRequest(RequestEvent $event) { $request = $event->getRequest(); // try to see if the locale has been set as a accept-language routing parameter if ($locale = $request->headers->get('accept-language')) { if ($this->isLocaleValid($locale) && in_array($locale, $this->supportedLocales)) { $request->setLocale($locale); } else { // if locale is not valid, use the default one $request->setLocale( $this->defaultLocale); } } else { // if no explicit locale has been set on this request, use the default one $request->setLocale( $this->defaultLocale); } $this->currentLocale = $request->getLocale(); } /** * @param ResponseEvent $event * @return Response */ public function setContentLanguage(ResponseEvent $event): Response { if (!isset($this->currentLocale)) { $this->currentLocale = $this->defaultLocale; } $response = $event->getResponse(); $response->headers->add(array('Content-Language' => $this->currentLocale)); return $response; } /** * @param $locale * @return bool */ private function isLocaleValid($locale): bool { $localeConstraint = new Locale(['canonicalize' => true]); $errors = $this->validator->validate($locale, $localeConstraint); return 0 == count($errors); }}