<?php
declare(strict_types=1);
namespace App\EventSubscriber\Under_maintenance;
use App\Entity\Security\RoleInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Security;
use Twig\Environment;
class UnderMaintenanceBoSubscriber implements EventSubscriberInterface
{
public function __construct(
private bool $isUnderMaintenance,
private string $apiRoutePrefix,
private Security $security,
private Environment $twig
) {
}
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => ['onKernelRequest', 1],
];
}
public function onKernelRequest(RequestEvent $event): void
{
if (false === $event->isMainRequest()) {
return;
}
if (false === $this->isUnderMaintenance) {
return;
}
$request = $event->getRequest();
if (str_starts_with($request->getPathInfo(), '/login')) {
return;
}
if (true === str_starts_with($request->getPathInfo(), $this->apiRoutePrefix)) {
return;
}
$user = $this->security->getUser();
if (
null === $user
|| \in_array(RoleInterface::ROLE_ADMIN, $user->getRoles(), true)
|| \in_array(RoleInterface::ROLE_PREVIOUS_ADMIN, $this->security->getToken()->getRoleNames(), true)
) {
return;
}
$html = $this->twig->render('under_maintenance.html.twig');
$event->setResponse(new Response($html, Response::HTTP_SERVICE_UNAVAILABLE));
}
}