src/EventListener/MaintenanceListener.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpKernel\Event\RequestEvent;
  4. use Twig\Environment;
  5. use Symfony\Component\HttpFoundation\Response;
  6. class MaintenanceListener {
  7.   /**
  8.    * The parameter that defines the maintenance object
  9.    *
  10.    * @var array
  11.    */
  12.   private $maintenance;
  13.   /**
  14.    * @var \Twig\Environment
  15.    */
  16.   private $twig;
  17.   /**
  18.    * Internal message to add some debugging into the twig template
  19.    *
  20.    * @var string
  21.    */
  22.   private $msg;
  23.   public function __construct($maintenanceEnvironment $twig) {
  24.     $this->maintenance $maintenance;
  25.     $this->twig $twig;
  26.   }
  27.   public function onKernelRequest(RequestEvent $event) {
  28.     if($this->isMaintenance()) {
  29.       // Creates the maintenance response object
  30.       $event->setResponse(
  31.           new Response(
  32.             $this->twig->render('lmdv/maintenance_page.html.twig', [
  33.                 'label' => 'maintenance.page.label',
  34.                 'errorMsg' => $this->msg
  35.             ]),
  36.             Response::HTTP_SERVICE_UNAVAILABLE
  37.           )
  38.       );
  39.       // End event processing
  40.       $event->stopPropagation();
  41.     }
  42.   }
  43.   protected function isMaintenance() {
  44.     // Stop here if we have not enabled maintenance functionality
  45.     if(! $this->maintenance['enabled']) {
  46.       return FALSE;
  47.     }
  48.     // First check condition by time intervals
  49.     date_default_timezone_set('Europe/Paris');
  50.     $start = \mktime($this->maintenance['start_hour'], $this->maintenance['start_minute']);
  51.     $end = \mktime($this->maintenance['end_hour'], $this->maintenance['end_minute']);
  52.     if($this->maintenance['start_hour'] > $this->maintenance['end_hour'])
  53.        $end = \mktime(23+$this->maintenance['end_hour'], $this->maintenance['end_minute']);    
  54.     date_default_timezone_set('UTC');
  55.     $current = \time();
  56.     if(($current >= $start) && ($current <= $end)) {
  57.       $this->msg "Current time $current is between $start and $end timestamps";
  58.       return TRUE;
  59.     }
  60.     // Check condition by .maintenance file
  61.     if(\file_exists($this->maintenance['maintenanceFilePath'])) {
  62.        $this->msg "Maintenance file was found in " $this->maintenance['maintenanceFilePath'];
  63.        return TRUE;
  64.     }
  65.     // Last resort, if we reach here assume no maintenance
  66.     return FALSE;
  67.   }
  68. }