<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\Setting;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment as TwigEnvironment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
class KernelRequestSubscriber implements EventSubscriberInterface
{
private $twig;
private $em;
public function __construct(TwigEnvironment $twig, EntityManagerInterface $em)
{
$this->twig = $twig;
$this->em = $em;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['onMaintenance', \PHP_INT_MAX - 1000],
],
];
}
/**
* @throws SyntaxError
* @throws RuntimeError
* @throws LoaderError
*/
public function onMaintenance(RequestEvent $event): Void
{
$isMaintenance = $this->em->getRepository(Setting::class)->findOneBy(['name' => 'maintenance_mode', 'type' => 'global']);
if ($isMaintenance !== null and $isMaintenance->getValue() == '0') {
$isMaintenance = false;
}
else {
$isMaintenance = true;
}
$isCli = \PHP_SAPI === 'cli';
if ($isMaintenance && !$isCli) {
$event->setResponse(new Response(
$this->twig->render('maintenance.html.twig'),
Response::HTTP_SERVICE_UNAVAILABLE,
));
$event->stopPropagation();
}
}
}