<?php
namespace App\EventListener;
use App\Service\Access as AccessService;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class MaintenanceListener
{
/** @var bool */
private $maintenance;
/** @var array */
private $ipAuthorized;
private AccessService $accessService;
public function __construct(array $maintenance, AccessService $accessService)
{
$this->accessService = $accessService;
$this->maintenance = $maintenance['statut'];
$this->ipAuthorized = $maintenance['ipAuthorized'];
}
public function onKernelRequest(RequestEvent $event): void
{
// This will get the value of our maintenance parameter
$maintenance = $this->maintenance ?: false;
$currentIP = null;
if (\array_key_exists('REMOTE_ADDR', $_SERVER)) {
$currentIP = $_SERVER['REMOTE_ADDR'];
}
// This will detect if we are in dev environment (app_dev.php)
// If maintenance is active and in prod environment
if ($maintenance === true && !\in_array($currentIP, $this->ipAuthorized, true)) {
// We load our maintenance template
// $event->setResponse(new Response($template, 503));
$response = $this->accessService->render('maintenance/maintenance.html.twig', [], 503);
// We send our response with a 503 response code (service unavailable)
$event->setResponse($response);
// $event->stopPropagation();
}
}
}