<?php
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Twig\Environment;
use Symfony\Component\HttpFoundation\Response;
class MaintenanceListener {
/**
* The parameter that defines the maintenance object
*
* @var array
*/
private $maintenance;
/**
* @var \Twig\Environment
*/
private $twig;
/**
* Internal message to add some debugging into the twig template
*
* @var string
*/
private $msg;
public function __construct($maintenance, Environment $twig) {
$this->maintenance = $maintenance;
$this->twig = $twig;
}
public function onKernelRequest(RequestEvent $event) {
if($this->isMaintenance()) {
// Creates the maintenance response object
$event->setResponse(
new Response(
$this->twig->render('lmdv/maintenance_page.html.twig', [
'label' => 'maintenance.page.label',
'errorMsg' => $this->msg
]),
Response::HTTP_SERVICE_UNAVAILABLE
)
);
// End event processing
$event->stopPropagation();
}
}
protected function isMaintenance() {
// Stop here if we have not enabled maintenance functionality
if(! $this->maintenance['enabled']) {
return FALSE;
}
// First check condition by time intervals
date_default_timezone_set('Europe/Paris');
$start = \mktime($this->maintenance['start_hour'], $this->maintenance['start_minute']);
$end = \mktime($this->maintenance['end_hour'], $this->maintenance['end_minute']);
if($this->maintenance['start_hour'] > $this->maintenance['end_hour'])
$end = \mktime(23+$this->maintenance['end_hour'], $this->maintenance['end_minute']);
date_default_timezone_set('UTC');
$current = \time();
if(($current >= $start) && ($current <= $end)) {
$this->msg = "Current time $current is between $start and $end timestamps";
return TRUE;
}
// Check condition by .maintenance file
if(\file_exists($this->maintenance['maintenanceFilePath'])) {
$this->msg = "Maintenance file was found in " . $this->maintenance['maintenanceFilePath'];
return TRUE;
}
// Last resort, if we reach here assume no maintenance
return FALSE;
}
}