<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use \Twig\Environment;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Platform;
class LocaleSubscriber implements EventSubscriberInterface
{
/**
* @var \Twig\Environment
*/
private $twig;
/**
* @var \Doctrine\ORM\EntityManager
*/
private $em;
public function __construct(Environment $twig, EntityManagerInterface $em, $defaultLocale = 'en')
{
$this->defaultLocale = $defaultLocale;
$this->twig = $twig;
$this->em = $em;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$platform = $this->em->getRepository(Platform::class)->findOneByDomain($_SERVER['HTTP_HOST']);
if (!$platform) {
die();
}
$request->getSession()->set('platform', $platform);
$this->twig->addGlobal('platform', $platform);
// 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 (!empty($request->getSession()->get('_locale'))) {
$locale = $request->getSession()->get('_locale');
} elseif (!empty($request->cookies->get('_locale'))) {
$locale = $request->cookies->get('_locale');
} elseif(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$locale = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}
if (!in_array($locale,array('en','fr')))
$locale = 'en';
$request->setLocale($locale);
}
}
public static function getSubscribedEvents()
{
return [
'kernel.request' => 'onKernelRequest',
];
}
}