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

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\InvalidArgumentException;
  15. use ApiPlatform\Core\Exception\RuntimeException;
  16. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
  17. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
  18. use ApiPlatform\Core\Util\RequestAttributesExtractor;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpFoundation\Response;
  21. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  22. use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
  23. use Twig\Environment as TwigEnvironment;
  24. /**
  25.  * Displays the documentation.
  26.  *
  27.  * @author Kévin Dunglas <dunglas@gmail.com>
  28.  */
  29. final class SwaggerUiAction
  30. {
  31.     private $resourceNameCollectionFactory;
  32.     private $resourceMetadataFactory;
  33.     private $normalizer;
  34.     private $twig;
  35.     private $urlGenerator;
  36.     private $title;
  37.     private $description;
  38.     private $version;
  39.     private $showWebby;
  40.     private $formats = [];
  41.     private $oauthEnabled;
  42.     private $oauthClientId;
  43.     private $oauthClientSecret;
  44.     private $oauthType;
  45.     private $oauthFlow;
  46.     private $oauthTokenUrl;
  47.     private $oauthAuthorizationUrl;
  48.     private $oauthScopes;
  49.     private $formatsProvider;
  50.     private $swaggerUiEnabled;
  51.     private $reDocEnabled;
  52.     private $graphqlEnabled;
  53.     /**
  54.      * @throws InvalidArgumentException
  55.      */
  56.     public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactoryResourceMetadataFactoryInterface $resourceMetadataFactoryNormalizerInterface $normalizerTwigEnvironment $twigUrlGeneratorInterface $urlGeneratorstring $title ''string $description ''string $version ''/* FormatsProviderInterface */ $formatsProvider = [], $oauthEnabled false$oauthClientId ''$oauthClientSecret ''$oauthType ''$oauthFlow ''$oauthTokenUrl ''$oauthAuthorizationUrl ''$oauthScopes = [], bool $showWebby truebool $swaggerUiEnabled falsebool $reDocEnabled falsebool $graphqlEnabled false)
  57.     {
  58.         $this->resourceNameCollectionFactory $resourceNameCollectionFactory;
  59.         $this->resourceMetadataFactory $resourceMetadataFactory;
  60.         $this->normalizer $normalizer;
  61.         $this->twig $twig;
  62.         $this->urlGenerator $urlGenerator;
  63.         $this->title $title;
  64.         $this->showWebby $showWebby;
  65.         $this->description $description;
  66.         $this->version $version;
  67.         $this->oauthEnabled $oauthEnabled;
  68.         $this->oauthClientId $oauthClientId;
  69.         $this->oauthClientSecret $oauthClientSecret;
  70.         $this->oauthType $oauthType;
  71.         $this->oauthFlow $oauthFlow;
  72.         $this->oauthTokenUrl $oauthTokenUrl;
  73.         $this->oauthAuthorizationUrl $oauthAuthorizationUrl;
  74.         $this->oauthScopes $oauthScopes;
  75.         $this->swaggerUiEnabled $swaggerUiEnabled;
  76.         $this->reDocEnabled $reDocEnabled;
  77.         $this->graphqlEnabled $graphqlEnabled;
  78.         if (\is_array($formatsProvider)) {
  79.             if ($formatsProvider) {
  80.                 // Only trigger notification for non-default argument
  81.                 @trigger_error('Using an array as formats provider is deprecated since API Platform 2.3 and will not be possible anymore in API Platform 3'E_USER_DEPRECATED);
  82.             }
  83.             $this->formats $formatsProvider;
  84.             return;
  85.         }
  86.         if (!$formatsProvider instanceof FormatsProviderInterface) {
  87.             throw new InvalidArgumentException(sprintf('The "$formatsProvider" argument is expected to be an implementation of the "%s" interface.'FormatsProviderInterface::class));
  88.         }
  89.         $this->formatsProvider $formatsProvider;
  90.     }
  91.     public function __invoke(Request $request)
  92.     {
  93.         // BC check to be removed in 3.0
  94.         if (null !== $this->formatsProvider) {
  95.             $this->formats $this->formatsProvider->getFormatsFromAttributes(RequestAttributesExtractor::extractAttributes($request));
  96.         }
  97.         $documentation = new Documentation($this->resourceNameCollectionFactory->create(), $this->title$this->description$this->version$this->formats);
  98.         return new Response($this->twig->render('@ApiPlatform/SwaggerUi/index.html.twig'$this->getContext($request$documentation)));
  99.     }
  100.     /**
  101.      * Gets the base Twig context.
  102.      */
  103.     private function getContext(Request $requestDocumentation $documentation): array
  104.     {
  105.         $context = [
  106.             'title' => $this->title,
  107.             'description' => $this->description,
  108.             'formats' => $this->formats,
  109.             'showWebby' => $this->showWebby,
  110.             'swaggerUiEnabled' => $this->swaggerUiEnabled,
  111.             'reDocEnabled' => $this->reDocEnabled,
  112.             'graphqlEnabled' => $this->graphqlEnabled,
  113.         ];
  114.         $swaggerContext = ['spec_version' => $request->query->getInt('spec_version'2)];
  115.         if ('' !== $baseUrl $request->getBaseUrl()) {
  116.             $swaggerContext['base_url'] = $baseUrl;
  117.         }
  118.         $swaggerData = [
  119.             'url' => $this->urlGenerator->generate('api_doc', ['format' => 'json']),
  120.             'spec' => $this->normalizer->normalize($documentation'json'$swaggerContext),
  121.         ];
  122.         $swaggerData['oauth'] = [
  123.             'enabled' => $this->oauthEnabled,
  124.             'clientId' => $this->oauthClientId,
  125.             'clientSecret' => $this->oauthClientSecret,
  126.             'type' => $this->oauthType,
  127.             'flow' => $this->oauthFlow,
  128.             'tokenUrl' => $this->oauthTokenUrl,
  129.             'authorizationUrl' => $this->oauthAuthorizationUrl,
  130.             'scopes' => $this->oauthScopes,
  131.         ];
  132.         if ($request->isMethodSafe(false) && null !== $resourceClass $request->attributes->get('_api_resource_class')) {
  133.             $swaggerData['id'] = $request->attributes->get('id');
  134.             $swaggerData['queryParameters'] = $request->query->all();
  135.             $metadata $this->resourceMetadataFactory->create($resourceClass);
  136.             $swaggerData['shortName'] = $metadata->getShortName();
  137.             if (null !== $collectionOperationName $request->attributes->get('_api_collection_operation_name')) {
  138.                 $swaggerData['operationId'] = sprintf('%s%sCollection'$collectionOperationNameucfirst($swaggerData['shortName']));
  139.             } elseif (null !== $itemOperationName $request->attributes->get('_api_item_operation_name')) {
  140.                 $swaggerData['operationId'] = sprintf('%s%sItem'$itemOperationNameucfirst($swaggerData['shortName']));
  141.             } elseif (null !== $subresourceOperationContext $request->attributes->get('_api_subresource_context')) {
  142.                 $swaggerData['operationId'] = $subresourceOperationContext['operationId'];
  143.             }
  144.             [$swaggerData['path'], $swaggerData['method']] = $this->getPathAndMethod($swaggerData);
  145.         }
  146.         return $context + ['swagger_data' => $swaggerData];
  147.     }
  148.     private function getPathAndMethod(array $swaggerData): array
  149.     {
  150.         foreach ($swaggerData['spec']['paths'] as $path => $operations) {
  151.             foreach ($operations as $method => $operation) {
  152.                 if ($operation['operationId'] === $swaggerData['operationId']) {
  153.                     return [$path$method];
  154.                 }
  155.             }
  156.         }
  157.         throw new RuntimeException(sprintf('The operation "%s" cannot be found in the Swagger specification.'$swaggerData['operationId']));
  158.     }
  159. }