src/EventListener/MaintenanceListener.php line 25

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  4. use Symfony\Component\DependencyInjection\ContainerInterface;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\Routing\RouterInterface;
  8. use Symfony\Contracts\Translation\TranslatorInterface;
  9. use Twig\Environment;
  10. use Twig\Template;
  11. class MaintenanceListener
  12. {
  13.     private $maintenance;
  14.     private $ipAuthorized;
  15.     public function __construct($maintenance, private ContainerInterface $container, private TranslatorInterface $translator, private RouterInterface $router, private Environment $twig)
  16.     {
  17.         $this->maintenance $maintenance["statut"];
  18.         $this->ipAuthorized $maintenance["ipAuthorized"];
  19.     }
  20.     public function onKernelRequest(RequestEvent $event)
  21.     {
  22.         // This will get the value of our maintenance parameter
  23.         $maintenance $this->maintenance ?: false;
  24.         $currentIP $_SERVER['REMOTE_ADDR'];
  25.         // This will detect if we are in dev environment (app_dev.php)
  26.         // $debug = in_array($this->container->get('kernel')->getEnvironment(), ['dev']);
  27.         // If maintenance is active and in prod environment
  28.         if ($maintenance and !in_array($currentIP$this->ipAuthorized)) {
  29.             $request $event->getRequest();
  30.             // Change user locale
  31.             $match $this->router->match($event->getRequest()->getPathInfo());
  32.             if ($match['_route'] == "change_lang") {
  33.                 $request->setLocale($match['lang']);
  34.                 $this->translator->setLocale($match['lang']);
  35.             }
  36.             // We load our maintenance template
  37.             $template $this->twig->render('maintenance/maintenance.html.twig');
  38.             // We send our response with a 503 response code (service unavailable)
  39.             $event->setResponse(new Response($template503));
  40.             $event->stopPropagation();
  41.         }
  42.     }
  43. }