src/EventListener/MaintenanceListener.php line 24

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Service\Access as AccessService;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. class MaintenanceListener
  6. {
  7.     /** @var bool */
  8.     private $maintenance;
  9.     /** @var array */
  10.     private $ipAuthorized;
  11.     private AccessService $accessService;
  12.     public function __construct(array $maintenanceAccessService $accessService)
  13.     {
  14.         $this->accessService $accessService;
  15.         $this->maintenance $maintenance['statut'];
  16.         $this->ipAuthorized $maintenance['ipAuthorized'];
  17.     }
  18.     public function onKernelRequest(RequestEvent $event): void
  19.     {
  20.         // This will get the value of our maintenance parameter
  21.         $maintenance $this->maintenance ?: false;
  22.         $currentIP null;
  23.         if (\array_key_exists('REMOTE_ADDR'$_SERVER)) {
  24.             $currentIP $_SERVER['REMOTE_ADDR'];
  25.         }
  26.         // This will detect if we are in dev environment (app_dev.php)
  27.         // If maintenance is active and in prod environment
  28.         if ($maintenance === true && !\in_array($currentIP$this->ipAuthorizedtrue)) {
  29.             // We load our maintenance template
  30.             // $event->setResponse(new Response($template, 503));
  31.             $response $this->accessService->render('maintenance/maintenance.html.twig', [], 503);
  32.             // We send our response with a 503 response code (service unavailable)
  33.             $event->setResponse($response);
  34.             // $event->stopPropagation();
  35.         }
  36.     }
  37. }