src/EventSubscriber/Under_maintenance/UnderMaintenanceApiSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber\Under_maintenance;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. class UnderMaintenanceApiSubscriber implements EventSubscriberInterface
  9. {
  10.     public function __construct(
  11.         private bool $isUnderMaintenance,
  12.         private string $apiRoutePrefix,
  13.     ) {
  14.     }
  15.     public static function getSubscribedEvents(): array
  16.     {
  17.         return [
  18.             RequestEvent::class => ['onKernelRequest'1],
  19.         ];
  20.     }
  21.     public function onKernelRequest(RequestEvent $event): void
  22.     {
  23.         if (false === $event->isMainRequest()) {
  24.             return;
  25.         }
  26.         if (false === $this->isUnderMaintenance) {
  27.             return;
  28.         }
  29.         if (false === str_starts_with($event->getRequest()->getPathInfo(), $this->apiRoutePrefix)) {
  30.             return;
  31.         }
  32.         $event->setResponse(
  33.             new JsonResponse(
  34.                 'Le système est actuellement en maintenance. Veuillez réessayer sous peu.',
  35.                 Response::HTTP_SERVICE_UNAVAILABLE
  36.             )
  37.         );
  38.     }
  39. }