src/EventSubscriber/SwaggerDocRequestEventSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. class SwaggerDocRequestEventSubscriber implements EventSubscriberInterface
  8. {
  9.     /** @var string[] $routesToRestrict Routes to deny when ENABLE_SWAGGER_DOCS is not true */
  10.     public static array $routesToRestrict = ['api_doc''api_entrypoint'];
  11.     /**
  12.      * Returns an array mapping events to functions to trigger.
  13.      * @return array The mapping array.
  14.      */
  15.     public static function getSubscribedEvents(): array
  16.     {
  17.         return [KernelEvents::REQUEST => 'restrictAccessToSwaggerDocumentation'];
  18.     }
  19.     /**
  20.      * Return an HTTP 404 if the ENABLE_SWAGGER_DOCS env variable is not at 'true' and the route is a documentation route.
  21.      * @param RequestEvent $event The HTTP Request event.
  22.      */
  23.     public function restrictAccessToSwaggerDocumentation(RequestEvent $event) {
  24.         if(true !== array_search($event->getRequest()->get('_route'), self::$routesToRestrict) && 'true' !== $_ENV['ENABLE_SWAGGER_DOCS']) {
  25.             $response = new Response();
  26.             $response->setStatusCode(Response::HTTP_NOT_FOUND);
  27.             $response->setContent("");
  28.             $event->setResponse($response);
  29.         }
  30.     }
  31. }