Skip to content

Instantly share code, notes, and snippets.

@MaxiCom
Forked from jfcherng/.env
Created May 10, 2023 23:54
Show Gist options
  • Save MaxiCom/6c425ba1a10a68a6dff7c9d035ff1389 to your computer and use it in GitHub Desktop.
Save MaxiCom/6c425ba1a10a68a6dff7c9d035ff1389 to your computer and use it in GitHub Desktop.
Symfony 5 maintenance mode
MAINTENANCE_MODE=0
<?php
declare(strict_types=1);
namespace App\EventSubscriber;
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;
class KernelRequestSubscriber implements EventSubscriberInterface
{
private TwigEnvironment $twig;
public function __construct(TwigEnvironment $twig)
{
$this->twig = $twig;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['onMaintenance', \PHP_INT_MAX - 1000],
],
];
}
public function onMaintenance(RequestEvent $event): void
{
/** @var bool $isMaintenance */
$isMaintenance = \filter_var($_ENV['MAINTENANCE_MODE'] ?? '0', \FILTER_VALIDATE_BOOLEAN);
$isCli = \PHP_SAPI === 'cli';
if ($isMaintenance && !$isCli) {
$event->setResponse(new Response(
$this->twig->render('maintenance.html.twig'),
Response::HTTP_SERVICE_UNAVAILABLE,
));
$event->stopPropagation();
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site temporarily under maintenance</title>
</head>
<body>
<h1>Site temporarily under maintenance</h1>
<p>Sorry for the inconvenience, we will get back soon!</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment