<?php
namespace App\EventListener;
use App\Component\Configuration\Util\Config;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
/**
* Class MaintenanceListener.
*
* Listens on the `kernel.request` event to redirect to the maintenance page is the site is set to maintenance status.
*/
class MaintenanceListener
{
private string $debug;
private Environment $twig;
private SessionInterface $session;
private ?Request $request;
private Config $config;
public function __construct(
string $debug,
SessionInterface $session,
Environment $twig,
RequestStack $requestStack,
Config $config
) {
$this->twig = $twig;
$this->debug = $debug;
$this->session = $session;
$this->request = $requestStack->getCurrentRequest();
$this->config = $config;
}
/**
* Redirects to the maintenance page if the site is set to maintenance status.
*
* Redirects non-admin requests to the maintenance page if
* 1. the site is set to maintenance status,
* 2. the site is not in dev environment, and
* 3. the user is not logged in (and is thus granted access).
*
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function onKernelRequest(RequestEvent $event)
{
// this is needed until code is seperated
if (0 === strncmp($this->request->getRequestUri(), '/admin', 6)) {
return;
}
// This will get the value of our maintenance parameter
$maintenance = 'maintenance' === $this->config->get('site_status');
// If maintenance is active and in prod environment
if ($maintenance && !$this->debug && !$this->session->get('site_access')) {
$response = $this->twig->render(
'@default/pages/maintenance.html.twig',
['maintenanceBody' => $this->config->get('site_maintenance_body')]
);
// We send our response with a 503 response code (service unavailable)
$event->setResponse(new Response($response, 503));
}
}
}