src/EventListener/MaintenanceListener.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpKernel\Event\RequestEvent;
  4. use Symfony\Component\DependencyInjection\ContainerInterface;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
  7. use Twig\Environment;
  8. use Twig\Error\LoaderError;
  9. use Twig\Error\RuntimeError;
  10. use Twig\Error\SyntaxError;
  11. class MaintenanceListener
  12. {
  13.     /**
  14.      * @var array
  15.      */
  16.     private $maintenance;
  17.     /**
  18.      * @var mixed
  19.      */
  20.     private $ipAuthorized;
  21.     /**
  22.      * @var Environment
  23.      */
  24.     private $twig;
  25.     public function __construct(array $maintenanceEnvironment $twig)
  26.     {
  27.         $this->maintenance $maintenance["statut"];
  28.         $this->ipAuthorized $maintenance["ipAuthorized"];
  29.         $this->twig $twig;
  30.     }
  31.     public function onKernelRequest(RequestEvent $event)
  32.     {
  33.         // This will get the value of our maintenance parameter
  34.         $maintenance $this->maintenance $this->maintenance false;
  35.         $currentIP $_SERVER['REMOTE_ADDR'];
  36.         // This will detect if we are in dev environment (app_dev.php)
  37.         // $debug = in_array($this->container->get('kernel')->getEnvironment(), ['dev']);
  38.         // If maintenance is active and in prod environment
  39.         if ($maintenance AND !in_array($currentIP$this->ipAuthorized)) {
  40.             // We load our maintenance template
  41.             $template '';
  42.             try {
  43.                 $template $this->twig->render('maintenance/maintenance.html.twig');
  44.             } catch (LoaderError $e) {
  45.                 throw new ServiceUnavailableHttpException();
  46.             } catch (RuntimeError $e) {
  47.             } catch (SyntaxError $e) {
  48.             }
  49.             // We send our response with a 503 response code (service unavailable)
  50.             $event->setResponse(new Response($template503));
  51.             $event->stopPropagation();
  52.         }
  53.     }
  54. }