<?php
declare(strict_types=1);
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
class LocaleListener implements EventSubscriberInterface {
protected $domain;
protected $domainLocales;
protected $defaultLocale;
public function __construct($container, $defaultLocale) {
$domain = $container->getParameter('domain');
$this->domainLocales = $container->getParameter('domain_locales');
$this->defaultLocale = $defaultLocale;
}
private function searchDomain($host) {
foreach($this->domainLocales as $k=>$v) {
if(is_array($v)) {
foreach($v as $k2=>$v2) {
if($host==$v2) return $k;
}
}
elseif($host==$v) return $k;
}
return $this->defaultLocale;
}
/**
* Set default locale
*
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event): void {
$request=$event->getRequest();
$locale=$this->searchDomain($request->getHost());
$request->setLocale($locale);
}
public function onKernelException(ExceptionEvent $event) {
$request=$event->getRequest();
//if (in_array($request->headers->get('Origin'), $this->allowed_subdomains)) {
$response = $event->getResponse();
//$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Allow-Headers', '*');
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');
$response->headers->set('Vary', 'Origin');
$event->setResponse($response);
// }
}
public function onKernelResponse(ResponseEvent $event) {
$request=$event->getRequest();
//if (in_array($request->headers->get('Origin'), $this->allowed_subdomains)) {
$response = $event->getResponse();
//$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Allow-Headers', '*');
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');
$response->headers->set('Vary', 'Origin');
$event->setResponse($response);
// }
}
/**
* {@inheritdoc}
*/
static public function getSubscribedEvents() {
return array(
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
/*return array(
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);}*/
}
}
?>