src/EventSubscriber/Under_maintenance/UnderMaintenanceBoSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber\Under_maintenance;
  4. use App\Entity\Security\RoleInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\Security\Core\Security;
  9. use Twig\Environment;
  10. class UnderMaintenanceBoSubscriber implements EventSubscriberInterface
  11. {
  12.     public function __construct(
  13.         private bool $isUnderMaintenance,
  14.         private string $apiRoutePrefix,
  15.         private Security $security,
  16.         private Environment $twig
  17.     ) {
  18.     }
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             RequestEvent::class => ['onKernelRequest'1],
  23.         ];
  24.     }
  25.     public function onKernelRequest(RequestEvent $event): void
  26.     {
  27.         if (false === $event->isMainRequest()) {
  28.             return;
  29.         }
  30.         if (false === $this->isUnderMaintenance) {
  31.             return;
  32.         }
  33.         $request $event->getRequest();
  34.         if (str_starts_with($request->getPathInfo(), '/login')) {
  35.             return;
  36.         }
  37.         if (true === str_starts_with($request->getPathInfo(), $this->apiRoutePrefix)) {
  38.             return;
  39.         }
  40.         $user $this->security->getUser();
  41.         if (
  42.             null === $user
  43.             || \in_array(RoleInterface::ROLE_ADMIN$user->getRoles(), true)
  44.             || \in_array(RoleInterface::ROLE_PREVIOUS_ADMIN$this->security->getToken()->getRoleNames(), true)
  45.         ) {
  46.             return;
  47.         }
  48.         $html $this->twig->render('under_maintenance.html.twig');
  49.         $event->setResponse(new Response($htmlResponse::HTTP_SERVICE_UNAVAILABLE));
  50.     }
  51. }