<?php
namespace App\EventSubscriber\Maintenance;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;
class MaintenanceSubscriber
{
private $logger;
private $twig;
private $underMaintenance;
public function __construct(LoggerInterface $logger, Environment $twig, $underMaintenance)
{
$this->logger = $logger;
$this->twig = $twig;
$this->underMaintenance = $underMaintenance;
}
public function onKernelRequest(RequestEvent $event)
{
// Check for UNDER_MAINTENANCE env var, if it is empty or false, then we can exit
if (!$this->underMaintenance || $this->strEquals($this->underMaintenance, 'false')) {
return;
}
// Check for if UNDER_MAINTENANCE is not set to true
if (!$this->strEquals($this->underMaintenance, 'true')) {
// Exit if we have an invalidate date
if (!$this->validateDate($this->underMaintenance)) {
return;
}
$underMaintenanceEndDate = strtotime($this->underMaintenance);
$now = new \DateTime();
// Exit if maintenance end date has passed
if ($now > $underMaintenanceEndDate) {
return;
}
}
// Final sanity check for if UNDER_MAINTENACE is true or a valid date
if ($this->strEquals($this->underMaintenance, 'true') || $this->validateDate(($this->underMaintenance))) {
// render page
$event->setResponse(new Response(
$this->twig->render('views/maintenance.html.twig'),
Response::HTTP_SERVICE_UNAVAILABLE,
));
$event->stopPropagation();
}
// Do nothing
}
private function strEquals($string, $value)
{
return strtoupper($string) === strtoupper($value);
}
private function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = \DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
}