vendor/api-platform/core/src/Symfony/Routing/ApiLoader.php line 243

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\Symfony\Routing;
  12. use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
  13. use ApiPlatform\Core\Api\OperationType;
  14. use ApiPlatform\Core\Bridge\Symfony\Routing\RouteNameGenerator;
  15. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
  16. use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
  17. use ApiPlatform\Core\Operation\Factory\SubresourceOperationFactoryInterface;
  18. use ApiPlatform\Exception\InvalidResourceException;
  19. use ApiPlatform\Exception\RuntimeException;
  20. use ApiPlatform\Metadata\CollectionOperationInterface;
  21. use ApiPlatform\Metadata\HttpOperation;
  22. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  23. use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
  24. use ApiPlatform\PathResolver\OperationPathResolverInterface;
  25. use Symfony\Component\Config\FileLocator;
  26. use Symfony\Component\Config\Loader\Loader;
  27. use Symfony\Component\Config\Resource\DirectoryResource;
  28. use Symfony\Component\DependencyInjection\ContainerInterface;
  29. use Symfony\Component\HttpKernel\KernelInterface;
  30. use Symfony\Component\Routing\Loader\XmlFileLoader;
  31. use Symfony\Component\Routing\Route;
  32. use Symfony\Component\Routing\RouteCollection;
  33. /**
  34.  * Loads Resources.
  35.  *
  36.  * @author Kévin Dunglas <dunglas@gmail.com>
  37.  */
  38. final class ApiLoader extends Loader
  39. {
  40.     /**
  41.      * @deprecated since version 2.1, to be removed in 3.0. Use {@see RouteNameGenerator::ROUTE_NAME_PREFIX} instead.
  42.      */
  43.     public const ROUTE_NAME_PREFIX 'api_';
  44.     public const DEFAULT_ACTION_PATTERN 'api_platform.action.';
  45.     private $fileLoader;
  46.     private $resourceNameCollectionFactory;
  47.     private $resourceMetadataFactory;
  48.     private $operationPathResolver;
  49.     private $container;
  50.     private $formats;
  51.     private $resourceClassDirectories;
  52.     private $subresourceOperationFactory;
  53.     private $graphqlEnabled;
  54.     private $graphiQlEnabled;
  55.     private $graphQlPlaygroundEnabled;
  56.     private $entrypointEnabled;
  57.     private $docsEnabled;
  58.     private $identifiersExtractor;
  59.     public function __construct(KernelInterface $kernelResourceNameCollectionFactoryInterface $resourceNameCollectionFactory$resourceMetadataFactoryOperationPathResolverInterface $operationPathResolverContainerInterface $container, array $formats, array $resourceClassDirectories = [], SubresourceOperationFactoryInterface $subresourceOperationFactory nullbool $graphqlEnabled falsebool $entrypointEnabled truebool $docsEnabled truebool $graphiQlEnabled falsebool $graphQlPlaygroundEnabled falseIdentifiersExtractorInterface $identifiersExtractor null)
  60.     {
  61.         /** @var string[]|string $paths */
  62.         $paths $kernel->locateResource('@ApiPlatformBundle/Resources/config/routing');
  63.         $this->fileLoader = new XmlFileLoader(new FileLocator($paths));
  64.         $this->resourceNameCollectionFactory $resourceNameCollectionFactory;
  65.         if ($resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) {
  66.             trigger_deprecation('api-platform/core''2.7'sprintf('Use "%s" instead of "%s".'ResourceMetadataCollectionFactoryInterface::class, ResourceMetadataFactoryInterface::class));
  67.         }
  68.         $this->resourceMetadataFactory $resourceMetadataFactory;
  69.         $this->operationPathResolver $operationPathResolver;
  70.         $this->container $container;
  71.         $this->formats $formats;
  72.         $this->resourceClassDirectories $resourceClassDirectories;
  73.         $this->subresourceOperationFactory $subresourceOperationFactory;
  74.         $this->graphqlEnabled $graphqlEnabled;
  75.         $this->graphiQlEnabled $graphiQlEnabled;
  76.         $this->graphQlPlaygroundEnabled $graphQlPlaygroundEnabled;
  77.         $this->entrypointEnabled $entrypointEnabled;
  78.         $this->docsEnabled $docsEnabled;
  79.         $this->identifiersExtractor $identifiersExtractor;
  80.     }
  81.     /**
  82.      * {@inheritdoc}
  83.      */
  84.     public function load($data$type null): RouteCollection
  85.     {
  86.         $routeCollection = new RouteCollection();
  87.         foreach ($this->resourceClassDirectories as $directory) {
  88.             $routeCollection->addResource(new DirectoryResource($directory'/\.php$/'));
  89.         }
  90.         $this->loadExternalFiles($routeCollection);
  91.         foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
  92.             if ($this->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) {
  93.                 $this->loadLegacyMetadata($routeCollection$resourceClass);
  94.                 $this->loadLegacySubresources($routeCollection$resourceClass);
  95.                 continue;
  96.             }
  97.             foreach ($this->resourceMetadataFactory->create($resourceClass) as $resourceMetadata) {
  98.                 foreach ($resourceMetadata->getOperations() as $operationName => $operation) {
  99.                     if ($operation->getRouteName()) {
  100.                         continue;
  101.                     }
  102.                     if (SkolemIriConverter::$skolemUriTemplate === $operation->getUriTemplate()) {
  103.                         continue;
  104.                     }
  105.                     $legacyDefaults = [];
  106.                     if ($operation->getExtraProperties()['is_legacy_subresource'] ?? false) {
  107.                         $legacyDefaults['_api_subresource_operation_name'] = $operationName;
  108.                         $legacyDefaults['_api_subresource_context'] = [
  109.                             'property' => $operation->getExtraProperties()['legacy_subresource_property'],
  110.                             'identifiers' => $operation->getExtraProperties()['legacy_subresource_identifiers'],
  111.                             'collection' => $operation instanceof CollectionOperationInterface,
  112.                             'operationId' => $operation->getExtraProperties()['legacy_subresource_operation_name'] ?? null,
  113.                         ];
  114.                         $legacyDefaults['_api_identifiers'] = $operation->getExtraProperties()['legacy_subresource_identifiers'];
  115.                     } elseif ($operation->getExtraProperties()['is_legacy_resource_metadata'] ?? false) {
  116.                         $legacyDefaults[sprintf('_api_%s_operation_name'$operation instanceof CollectionOperationInterface OperationType::COLLECTION OperationType::ITEM)] = $operationName;
  117.                         $legacyDefaults['_api_identifiers'] = [];
  118.                         // Legacy identifiers
  119.                         $hasCompositeIdentifier false;
  120.                         foreach ($operation->getUriVariables() ?? [] as $parameterName => $identifiedBy) {
  121.                             $hasCompositeIdentifier $identifiedBy->getCompositeIdentifier();
  122.                             foreach ($identifiedBy->getIdentifiers() ?? [] as $identifier) {
  123.                                 $legacyDefaults['_api_identifiers'][] = $identifier;
  124.                             }
  125.                         }
  126.                         $legacyDefaults['_api_has_composite_identifier'] = $hasCompositeIdentifier;
  127.                     }
  128.                     $path = ($operation->getRoutePrefix() ?? '').$operation->getUriTemplate();
  129.                     foreach ($operation->getUriVariables() ?? [] as $parameterName => $link) {
  130.                         if (!$expandedValue $link->getExpandedValue()) {
  131.                             continue;
  132.                         }
  133.                         $path str_replace(sprintf('{%s}'$parameterName), $expandedValue$path);
  134.                     }
  135.                     $route = new Route(
  136.                         $path,
  137.                         $legacyDefaults + [
  138.                             '_controller' => $operation->getController() ?? 'api_platform.action.placeholder',
  139.                             '_format' => null,
  140.                             '_stateless' => $operation->getStateless(),
  141.                             '_api_resource_class' => $resourceClass,
  142.                             '_api_operation_name' => $operationName,
  143.                         ] + ($operation->getDefaults() ?? []),
  144.                         $operation->getRequirements() ?? [],
  145.                         $operation->getOptions() ?? [],
  146.                         $operation->getHost() ?? '',
  147.                         $operation->getSchemes() ?? [],
  148.                         [$operation->getMethod() ?? HttpOperation::METHOD_GET],
  149.                         $operation->getCondition() ?? ''
  150.                     );
  151.                     $routeCollection->add($operationName$route);
  152.                 }
  153.             }
  154.         }
  155.         return $routeCollection;
  156.     }
  157.     /**
  158.      * {@inheritdoc}
  159.      */
  160.     public function supports($resource$type null): bool
  161.     {
  162.         return 'api_platform' === $type;
  163.     }
  164.     /**
  165.      * Load external files.
  166.      */
  167.     private function loadExternalFiles(RouteCollection $routeCollection): void
  168.     {
  169.         $routeCollection->addCollection($this->fileLoader->load('genid.xml'));
  170.         if ($this->entrypointEnabled) {
  171.             $routeCollection->addCollection($this->fileLoader->load('api.xml'));
  172.         }
  173.         if ($this->docsEnabled) {
  174.             $routeCollection->addCollection($this->fileLoader->load('docs.xml'));
  175.         }
  176.         if ($this->graphqlEnabled) {
  177.             $graphqlCollection $this->fileLoader->load('graphql/graphql.xml');
  178.             $graphqlCollection->addDefaults(['_graphql' => true]);
  179.             $routeCollection->addCollection($graphqlCollection);
  180.         }
  181.         if ($this->graphiQlEnabled) {
  182.             $graphiQlCollection $this->fileLoader->load('graphql/graphiql.xml');
  183.             $graphiQlCollection->addDefaults(['_graphql' => true]);
  184.             $routeCollection->addCollection($graphiQlCollection);
  185.         }
  186.         if ($this->graphQlPlaygroundEnabled) {
  187.             $graphQlPlaygroundCollection $this->fileLoader->load('graphql/graphql_playground.xml');
  188.             $graphQlPlaygroundCollection->addDefaults(['_graphql' => true]);
  189.             $routeCollection->addCollection($graphQlPlaygroundCollection);
  190.         }
  191.         if (isset($this->formats['jsonld'])) {
  192.             $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
  193.         }
  194.     }
  195.     /**
  196.      * TODO: remove in 3.0.
  197.      */
  198.     private function loadLegacyMetadata(RouteCollection $routeCollectionstring $resourceClass)
  199.     {
  200.         $resourceMetadata $this->resourceMetadataFactory->create($resourceClass);
  201.         $resourceShortName $resourceMetadata->getShortName();
  202.         if (null === $resourceShortName) {
  203.             throw new InvalidResourceException(sprintf('Resource %s has no short name defined.'$resourceClass));
  204.         }
  205.         if (null !== $collectionOperations $resourceMetadata->getCollectionOperations()) {
  206.             foreach ($collectionOperations as $operationName => $operation) {
  207.                 $this->addRoute($routeCollection$resourceClass$operationName$operation$resourceMetadataOperationType::COLLECTION);
  208.             }
  209.         }
  210.         if (null !== $itemOperations $resourceMetadata->getItemOperations()) {
  211.             foreach ($itemOperations as $operationName => $operation) {
  212.                 $this->addRoute($routeCollection$resourceClass$operationName$operation$resourceMetadataOperationType::ITEM);
  213.             }
  214.         }
  215.     }
  216.     /**
  217.      * TODO: remove in 3.0.
  218.      */
  219.     private function loadLegacySubresources(RouteCollection $routeCollectionstring $resourceClass)
  220.     {
  221.         if (null === $this->subresourceOperationFactory) {
  222.             return;
  223.         }
  224.         foreach ($this->subresourceOperationFactory->create($resourceClass) as $operationId => $operation) {
  225.             if (null === $controller $operation['controller'] ?? null) {
  226.                 $controller self::DEFAULT_ACTION_PATTERN.'get_subresource';
  227.                 if (!$this->container->has($controller)) {
  228.                     throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.'OperationType::SUBRESOURCE'GET'));
  229.                 }
  230.             }
  231.             $routeCollection->add($operation['route_name'], new Route(
  232.                 $operation['path'],
  233.                 [
  234.                     '_controller' => $controller,
  235.                     '_format' => $operation['defaults']['_format'] ?? null,
  236.                     '_stateless' => $operation['stateless'] ?? null,
  237.                     '_api_resource_class' => $operation['resource_class'],
  238.                     '_api_identifiers' => $operation['identifiers'],
  239.                     '_api_has_composite_identifier' => false,
  240.                     '_api_subresource_operation_name' => $operation['route_name'],
  241.                     '_api_subresource_context' => [
  242.                         'property' => $operation['property'],
  243.                         'identifiers' => $operation['identifiers'],
  244.                         'collection' => $operation['collection'],
  245.                         'operationId' => $operationId,
  246.                     ],
  247.                 ] + ($operation['defaults'] ?? []),
  248.                 $operation['requirements'] ?? [],
  249.                 $operation['options'] ?? [],
  250.                 $operation['host'] ?? '',
  251.                 $operation['schemes'] ?? [],
  252.                 ['GET'],
  253.                 $operation['condition'] ?? ''
  254.             ));
  255.         }
  256.     }
  257.     /**
  258.      * Creates and adds a route for the given operation to the route collection.
  259.      *
  260.      * @throws RuntimeException
  261.      */
  262.     private function addRoute(RouteCollection $routeCollectionstring $resourceClassstring $operationName, array $operationResourceMetadata $resourceMetadatastring $operationType): void
  263.     {
  264.         $resourceShortName $resourceMetadata->getShortName();
  265.         if (isset($operation['route_name'])) {
  266.             if (!isset($operation['method'])) {
  267.                 @trigger_error(sprintf('Not setting the "method" attribute is deprecated and will not be supported anymore in API Platform 3.0, set it for the %s operation "%s" of the class "%s".'OperationType::COLLECTION === $operationType 'collection' 'item'$operationName$resourceClass), \E_USER_DEPRECATED);
  268.             }
  269.             return;
  270.         }
  271.         if (!isset($operation['method'])) {
  272.             throw new RuntimeException(sprintf('Either a "route_name" or a "method" operation attribute must exist for the operation "%s" of the resource "%s".'$operationName$resourceClass));
  273.         }
  274.         if (null === $controller $operation['controller'] ?? null) {
  275.             $controller sprintf('%s%s_%s'self::DEFAULT_ACTION_PATTERNstrtolower($operation['method']), $operationType);
  276.             if (!$this->container->has($controller)) {
  277.                 throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.'$operationType$operation['method']));
  278.             }
  279.         }
  280.         if ($resourceMetadata->getItemOperations()) {
  281.             $operation['identifiers'] = (array) ($operation['identifiers'] ?? $resourceMetadata->getAttribute('identifiers'$this->identifiersExtractor $this->identifiersExtractor->getIdentifiersFromResourceClass($resourceClass) : ['id']));
  282.         }
  283.         $operation['has_composite_identifier'] = isset($operation['identifiers']) && \count($operation['identifiers']) > $resourceMetadata->getAttribute('composite_identifier'true) : false;
  284.         $path trim(trim($resourceMetadata->getAttribute('route_prefix''')), '/');
  285.         $path .= $this->operationPathResolver->resolveOperationPath($resourceShortName$operation$operationType$operationName);
  286.         $route = new Route(
  287.             $path,
  288.             [
  289.                 '_controller' => $controller,
  290.                 '_format' => $operation['defaults']['_format'] ?? null,
  291.                 '_stateless' => $operation['stateless'] ?? null,
  292.                 '_api_resource_class' => $resourceClass,
  293.                 '_api_identifiers' => $operation['identifiers'] ?? [],
  294.                 '_api_has_composite_identifier' => $operation['has_composite_identifier'] ?? true,
  295.                 '_api_exception_to_status' => $operation['exception_to_status'] ?? $resourceMetadata->getAttribute('exception_to_status') ?? [],
  296.                 '_api_operation_name' => RouteNameGenerator::generate($operationName$resourceShortName$operationType),
  297.                 sprintf('_api_%s_operation_name'$operationType) => $operationName,
  298.             ] + ($operation['defaults'] ?? []),
  299.             $operation['requirements'] ?? [],
  300.             $operation['options'] ?? [],
  301.             $operation['host'] ?? '',
  302.             $operation['schemes'] ?? [],
  303.             [$operation['method']],
  304.             $operation['condition'] ?? ''
  305.         );
  306.         $routeCollection->add(RouteNameGenerator::generate($operationName$resourceShortName$operationType), $route);
  307.     }
  308. }
  309. class_alias(ApiLoader::class, \ApiPlatform\Core\Bridge\Symfony\Routing\ApiLoader::class);