<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class SetLanguageCookieSubscriber implements EventSubscriberInterface
{
public function onKernelResponse(ResponseEvent $event)
{
$request = $event->getRequest();
if (!$event->isMasterRequest()) {
return;
}
if ($request->attributes->get('_route') == '_wdt') {
return;
}
if ($request->getPathInfo() && strpos($request->getPathInfo(), '_wdt') !== false) {
return;
}
$newUrl = strtolower($request->getPathInfo());
if (preg_match_all("/js\/routing/", $newUrl) || preg_match_all("/[a-z]{2}\/notifications\/widget/", $newUrl)
|| $newUrl === '/' || preg_match_all("#/_fragment#", $newUrl)) {
return;
}
$response = $event->getResponse();
$locale = $event->getRequest()->getLocale();
$response->headers->setCookie(new Cookie('preferred_language', $locale));
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::RESPONSE => [['onKernelResponse', -1050]],
];
}
}