vendor/api-platform/core/src/Bridge/Symfony/Bundle/Action/SwaggerUiAction.php line 33

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the API Platform project.
  4.  *
  5.  * (c) Kévin Dunglas <dunglas@gmail.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace ApiPlatform\Core\Bridge\Symfony\Bundle\Action;
  12. use ApiPlatform\Core\Api\FormatsProviderInterface;
  13. use ApiPlatform\Core\Documentation\Documentation;
  14. use ApiPlatform\Core\Exception\RuntimeException;
  15. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
  16. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
  17. use ApiPlatform\Core\Util\RequestAttributesExtractor;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  21. use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
  22. use Twig\Environment as TwigEnvironment;
  23. /**
  24.  * Displays the documentation.
  25.  *
  26.  * @author Kévin Dunglas <dunglas@gmail.com>
  27.  */
  28. final class SwaggerUiAction
  29. {
  30.     private $resourceNameCollectionFactory;
  31.     private $resourceMetadataFactory;
  32.     private $normalizer;
  33.     private $twig;
  34.     private $urlGenerator;
  35.     private $title;
  36.     private $description;
  37.     private $version;
  38.     private $showWebby;
  39.     private $formats;
  40.     private $oauthEnabled;
  41.     private $oauthClientId;
  42.     private $oauthClientSecret;
  43.     private $oauthType;
  44.     private $oauthFlow;
  45.     private $oauthTokenUrl;
  46.     private $oauthAuthorizationUrl;
  47.     private $oauthScopes;
  48.     private $formatsProvider;
  49.     private $swaggerUiEnabled;
  50.     private $reDocEnabled;
  51.     private $graphqlEnabled;
  52.     private $graphiQlEnabled;
  53.     private $graphQlPlaygroundEnabled;
  54.     private $swaggerVersions;
  55.     /**
  56.      * @param int[] $swaggerVersions
  57.      */
  58.     public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactoryResourceMetadataFactoryInterface $resourceMetadataFactoryNormalizerInterface $normalizerTwigEnvironment $twigUrlGeneratorInterface $urlGeneratorstring $title ''string $description ''string $version ''$formats = [], $oauthEnabled false$oauthClientId ''$oauthClientSecret ''$oauthType ''$oauthFlow ''$oauthTokenUrl ''$oauthAuthorizationUrl ''$oauthScopes = [], bool $showWebby truebool $swaggerUiEnabled falsebool $reDocEnabled falsebool $graphqlEnabled falsebool $graphiQlEnabled falsebool $graphQlPlaygroundEnabled false, array $swaggerVersions = [23])
  59.     {
  60.         $this->resourceNameCollectionFactory $resourceNameCollectionFactory;
  61.         $this->resourceMetadataFactory $resourceMetadataFactory;
  62.         $this->normalizer $normalizer;
  63.         $this->twig $twig;
  64.         $this->urlGenerator $urlGenerator;
  65.         $this->title $title;
  66.         $this->showWebby $showWebby;
  67.         $this->description $description;
  68.         $this->version $version;
  69.         $this->oauthEnabled $oauthEnabled;
  70.         $this->oauthClientId $oauthClientId;
  71.         $this->oauthClientSecret $oauthClientSecret;
  72.         $this->oauthType $oauthType;
  73.         $this->oauthFlow $oauthFlow;
  74.         $this->oauthTokenUrl $oauthTokenUrl;
  75.         $this->oauthAuthorizationUrl $oauthAuthorizationUrl;
  76.         $this->oauthScopes $oauthScopes;
  77.         $this->swaggerUiEnabled $swaggerUiEnabled;
  78.         $this->reDocEnabled $reDocEnabled;
  79.         $this->graphqlEnabled $graphqlEnabled;
  80.         $this->graphiQlEnabled $graphiQlEnabled;
  81.         $this->graphQlPlaygroundEnabled $graphQlPlaygroundEnabled;
  82.         $this->swaggerVersions $swaggerVersions;
  83.         if (\is_array($formats)) {
  84.             $this->formats $formats;
  85.             return;
  86.         }
  87.         @trigger_error(sprintf('Passing an array or an instance of "%s" as 5th parameter of the constructor of "%s" is deprecated since API Platform 2.5, pass an array instead'FormatsProviderInterface::class, __CLASS__), E_USER_DEPRECATED);
  88.         $this->formatsProvider $formats;
  89.     }
  90.     public function __invoke(Request $request)
  91.     {
  92.         $attributes RequestAttributesExtractor::extractAttributes($request);
  93.         // BC check to be removed in 3.0
  94.         if (null === $this->formatsProvider) {
  95.             $formats $attributes $this
  96.                 ->resourceMetadataFactory
  97.                 ->create($attributes['resource_class'])
  98.                 ->getOperationAttribute($attributes'output_formats', [], true) : $this->formats;
  99.         } else {
  100.             $formats $this->formatsProvider->getFormatsFromAttributes($attributes);
  101.         }
  102.         $documentation = new Documentation($this->resourceNameCollectionFactory->create(), $this->title$this->description$this->version);
  103.         return new Response($this->twig->render('@ApiPlatform/SwaggerUi/index.html.twig'$this->getContext($request$documentation) + ['formats' => $formats]));
  104.     }
  105.     /**
  106.      * Gets the base Twig context.
  107.      */
  108.     private function getContext(Request $requestDocumentation $documentation): array
  109.     {
  110.         $context = [
  111.             'title' => $this->title,
  112.             'description' => $this->description,
  113.             'showWebby' => $this->showWebby,
  114.             'swaggerUiEnabled' => $this->swaggerUiEnabled,
  115.             'reDocEnabled' => $this->reDocEnabled,
  116.             'graphqlEnabled' => $this->graphqlEnabled,
  117.             'graphiQlEnabled' => $this->graphiQlEnabled,
  118.             'graphQlPlaygroundEnabled' => $this->graphQlPlaygroundEnabled,
  119.         ];
  120.         $swaggerContext = ['spec_version' => $request->query->getInt('spec_version'$this->swaggerVersions[0] ?? 2)];
  121.         if ('' !== $baseUrl $request->getBaseUrl()) {
  122.             $swaggerContext['base_url'] = $baseUrl;
  123.         }
  124.         $swaggerData = [
  125.             'url' => $this->urlGenerator->generate('api_doc', ['format' => 'json']),
  126.             'spec' => $this->normalizer->normalize($documentation'json'$swaggerContext),
  127.         ];
  128.         $swaggerData['oauth'] = [
  129.             'enabled' => $this->oauthEnabled,
  130.             'clientId' => $this->oauthClientId,
  131.             'clientSecret' => $this->oauthClientSecret,
  132.             'type' => $this->oauthType,
  133.             'flow' => $this->oauthFlow,
  134.             'tokenUrl' => $this->oauthTokenUrl,
  135.             'authorizationUrl' => $this->oauthAuthorizationUrl,
  136.             'scopes' => $this->oauthScopes,
  137.         ];
  138.         if ($request->isMethodSafe() && null !== $resourceClass $request->attributes->get('_api_resource_class')) {
  139.             $swaggerData['id'] = $request->attributes->get('id');
  140.             $swaggerData['queryParameters'] = $request->query->all();
  141.             $metadata $this->resourceMetadataFactory->create($resourceClass);
  142.             $swaggerData['shortName'] = $metadata->getShortName();
  143.             if (null !== $collectionOperationName $request->attributes->get('_api_collection_operation_name')) {
  144.                 $swaggerData['operationId'] = sprintf('%s%sCollection'$collectionOperationNameucfirst($swaggerData['shortName']));
  145.             } elseif (null !== $itemOperationName $request->attributes->get('_api_item_operation_name')) {
  146.                 $swaggerData['operationId'] = sprintf('%s%sItem'$itemOperationNameucfirst($swaggerData['shortName']));
  147.             } elseif (null !== $subresourceOperationContext $request->attributes->get('_api_subresource_context')) {
  148.                 $swaggerData['operationId'] = $subresourceOperationContext['operationId'];
  149.             }
  150.             [$swaggerData['path'], $swaggerData['method']] = $this->getPathAndMethod($swaggerData);
  151.         }
  152.         return $context + ['swagger_data' => $swaggerData];
  153.     }
  154.     private function getPathAndMethod(array $swaggerData): array
  155.     {
  156.         foreach ($swaggerData['spec']['paths'] as $path => $operations) {
  157.             foreach ($operations as $method => $operation) {
  158.                 if ($operation['operationId'] === $swaggerData['operationId']) {
  159.                     return [$path$method];
  160.                 }
  161.             }
  162.         }
  163.         throw new RuntimeException(sprintf('The operation "%s" cannot be found in the Swagger specification.'$swaggerData['operationId']));
  164.     }
  165. }