<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class SwaggerDocRequestEventSubscriber implements EventSubscriberInterface
{
/** @var string[] $routesToRestrict Routes to deny when ENABLE_SWAGGER_DOCS is not true */
public static array $routesToRestrict = ['api_doc', 'api_entrypoint'];
/**
* Returns an array mapping events to functions to trigger.
* @return array The mapping array.
*/
public static function getSubscribedEvents(): array
{
return [KernelEvents::REQUEST => 'restrictAccessToSwaggerDocumentation'];
}
/**
* Return an HTTP 404 if the ENABLE_SWAGGER_DOCS env variable is not at 'true' and the route is a documentation route.
* @param RequestEvent $event The HTTP Request event.
*/
public function restrictAccessToSwaggerDocumentation(RequestEvent $event) {
if(true !== array_search($event->getRequest()->get('_route'), self::$routesToRestrict) && 'true' !== $_ENV['ENABLE_SWAGGER_DOCS']) {
$response = new Response();
$response->setStatusCode(Response::HTTP_NOT_FOUND);
$response->setContent("");
$event->setResponse($response);
}
}
}