<?php
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
use Twig\Template;
class MaintenanceListener
{
private $maintenance;
private $ipAuthorized;
public function __construct($maintenance, private ContainerInterface $container, private TranslatorInterface $translator, private RouterInterface $router, private Environment $twig)
{
$this->maintenance = $maintenance["statut"];
$this->ipAuthorized = $maintenance["ipAuthorized"];
}
public function onKernelRequest(RequestEvent $event)
{
// This will get the value of our maintenance parameter
$maintenance = $this->maintenance ?: false;
$currentIP = $_SERVER['REMOTE_ADDR'];
// This will detect if we are in dev environment (app_dev.php)
// $debug = in_array($this->container->get('kernel')->getEnvironment(), ['dev']);
// If maintenance is active and in prod environment
if ($maintenance and !in_array($currentIP, $this->ipAuthorized)) {
$request = $event->getRequest();
// Change user locale
$match = $this->router->match($event->getRequest()->getPathInfo());
if ($match['_route'] == "change_lang") {
$request->setLocale($match['lang']);
$this->translator->setLocale($match['lang']);
}
// We load our maintenance template
$template = $this->twig->render('maintenance/maintenance.html.twig');
// We send our response with a 503 response code (service unavailable)
$event->setResponse(new Response($template, 503));
$event->stopPropagation();
}
}
}