<?php
namespace App\EventSubscriber;
use App\Service\ParamService;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
class MaintenanceSubscriber implements EventSubscriberInterface
{
public function __construct(
private ParamService $paramService,
private RouterInterface $router,
private ParameterBagInterface $params
) {
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$maintenanceValue = $this->paramService->get('site_maintenance', false);
$maintenanceEnabled = filter_var($maintenanceValue, FILTER_VALIDATE_BOOLEAN);
$request = $event->getRequest();
$route = $request->attributes->get('_route');
$path = $request->getPathInfo();
if (!$maintenanceEnabled) {
if ($route === 'maintenance') {
$event->setResponse(new RedirectResponse($this->router->generate('home')));
}
return;
}
if (
$route === 'maintenance'
|| str_starts_with($path, '/admin')
|| str_starts_with($path, '/ajax')
|| str_starts_with($path, '/_profiler')
) {
return;
}
$event->setResponse(new RedirectResponse($this->router->generate('maintenance')));
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 15],
];
}
}