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

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\Routing;
  12. use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
  13. use ApiPlatform\Core\Api\OperationType;
  14. use ApiPlatform\Core\Exception\InvalidResourceException;
  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\Metadata\Resource\ResourceMetadata;
  19. use ApiPlatform\Core\Operation\Factory\SubresourceOperationFactoryInterface;
  20. use ApiPlatform\Core\PathResolver\OperationPathResolverInterface;
  21. use Symfony\Component\Config\FileLocator;
  22. use Symfony\Component\Config\Loader\Loader;
  23. use Symfony\Component\Config\Resource\DirectoryResource;
  24. use Symfony\Component\DependencyInjection\ContainerInterface;
  25. use Symfony\Component\HttpKernel\KernelInterface;
  26. use Symfony\Component\Routing\Loader\XmlFileLoader;
  27. use Symfony\Component\Routing\Route;
  28. use Symfony\Component\Routing\RouteCollection;
  29. /**
  30.  * Loads Resources.
  31.  *
  32.  * @author Kévin Dunglas <dunglas@gmail.com>
  33.  */
  34. final class ApiLoader extends Loader
  35. {
  36.     /**
  37.      * @deprecated since version 2.1, to be removed in 3.0. Use {@see RouteNameGenerator::ROUTE_NAME_PREFIX} instead.
  38.      */
  39.     public const ROUTE_NAME_PREFIX 'api_';
  40.     public const DEFAULT_ACTION_PATTERN 'api_platform.action.';
  41.     private $fileLoader;
  42.     private $resourceNameCollectionFactory;
  43.     private $resourceMetadataFactory;
  44.     private $operationPathResolver;
  45.     private $container;
  46.     private $formats;
  47.     private $resourceClassDirectories;
  48.     private $subresourceOperationFactory;
  49.     private $graphqlEnabled;
  50.     private $graphiQlEnabled;
  51.     private $graphQlPlaygroundEnabled;
  52.     private $entrypointEnabled;
  53.     private $docsEnabled;
  54.     private $identifiersExtractor;
  55.     public function __construct(KernelInterface $kernelResourceNameCollectionFactoryInterface $resourceNameCollectionFactoryResourceMetadataFactoryInterface $resourceMetadataFactoryOperationPathResolverInterface $operationPathResolverContainerInterface $container, array $formats, array $resourceClassDirectories = [], SubresourceOperationFactoryInterface $subresourceOperationFactory nullbool $graphqlEnabled falsebool $entrypointEnabled truebool $docsEnabled truebool $graphiQlEnabled falsebool $graphQlPlaygroundEnabled falseIdentifiersExtractorInterface $identifiersExtractor null)
  56.     {
  57.         /** @var string[]|string $paths */
  58.         $paths $kernel->locateResource('@ApiPlatformBundle/Resources/config/routing');
  59.         $this->fileLoader = new XmlFileLoader(new FileLocator($paths));
  60.         $this->resourceNameCollectionFactory $resourceNameCollectionFactory;
  61.         $this->resourceMetadataFactory $resourceMetadataFactory;
  62.         $this->operationPathResolver $operationPathResolver;
  63.         $this->container $container;
  64.         $this->formats $formats;
  65.         $this->resourceClassDirectories $resourceClassDirectories;
  66.         $this->subresourceOperationFactory $subresourceOperationFactory;
  67.         $this->graphqlEnabled $graphqlEnabled;
  68.         $this->graphiQlEnabled $graphiQlEnabled;
  69.         $this->graphQlPlaygroundEnabled $graphQlPlaygroundEnabled;
  70.         $this->entrypointEnabled $entrypointEnabled;
  71.         $this->docsEnabled $docsEnabled;
  72.         $this->identifiersExtractor $identifiersExtractor;
  73.     }
  74.     /**
  75.      * {@inheritdoc}
  76.      */
  77.     public function load($data$type null): RouteCollection
  78.     {
  79.         $routeCollection = new RouteCollection();
  80.         foreach ($this->resourceClassDirectories as $directory) {
  81.             $routeCollection->addResource(new DirectoryResource($directory'/\.php$/'));
  82.         }
  83.         $this->loadExternalFiles($routeCollection);
  84.         foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
  85.             $resourceMetadata $this->resourceMetadataFactory->create($resourceClass);
  86.             $resourceShortName $resourceMetadata->getShortName();
  87.             if (null === $resourceShortName) {
  88.                 throw new InvalidResourceException(sprintf('Resource %s has no short name defined.'$resourceClass));
  89.             }
  90.             if (null !== $collectionOperations $resourceMetadata->getCollectionOperations()) {
  91.                 foreach ($collectionOperations as $operationName => $operation) {
  92.                     $this->addRoute($routeCollection$resourceClass$operationName$operation$resourceMetadataOperationType::COLLECTION);
  93.                 }
  94.             }
  95.             if (null !== $itemOperations $resourceMetadata->getItemOperations()) {
  96.                 foreach ($itemOperations as $operationName => $operation) {
  97.                     $this->addRoute($routeCollection$resourceClass$operationName$operation$resourceMetadataOperationType::ITEM);
  98.                 }
  99.             }
  100.             if (null === $this->subresourceOperationFactory) {
  101.                 continue;
  102.             }
  103.             foreach ($this->subresourceOperationFactory->create($resourceClass) as $operationId => $operation) {
  104.                 if (null === $controller $operation['controller'] ?? null) {
  105.                     $controller self::DEFAULT_ACTION_PATTERN.'get_subresource';
  106.                     if (!$this->container->has($controller)) {
  107.                         throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.'OperationType::SUBRESOURCE'GET'));
  108.                     }
  109.                 }
  110.                 $routeCollection->add($operation['route_name'], new Route(
  111.                     $operation['path'],
  112.                     [
  113.                         '_controller' => $controller,
  114.                         '_format' => null,
  115.                         '_stateless' => $operation['stateless'] ?? $resourceMetadata->getAttribute('stateless'),
  116.                         '_api_resource_class' => $operation['resource_class'],
  117.                         '_api_identifiers' => $operation['identifiers'],
  118.                         '_api_has_composite_identifier' => false,
  119.                         '_api_subresource_operation_name' => $operation['route_name'],
  120.                         '_api_subresource_context' => [
  121.                             'property' => $operation['property'],
  122.                             'identifiers' => $operation['identifiers'],
  123.                             'collection' => $operation['collection'],
  124.                             'operationId' => $operationId,
  125.                         ],
  126.                     ] + ($operation['defaults'] ?? []),
  127.                     $operation['requirements'] ?? [],
  128.                     $operation['options'] ?? [],
  129.                     $operation['host'] ?? '',
  130.                     $operation['schemes'] ?? [],
  131.                     ['GET'],
  132.                     $operation['condition'] ?? ''
  133.                 ));
  134.             }
  135.         }
  136.         return $routeCollection;
  137.     }
  138.     /**
  139.      * {@inheritdoc}
  140.      */
  141.     public function supports($resource$type null): bool
  142.     {
  143.         return 'api_platform' === $type;
  144.     }
  145.     /**
  146.      * Load external files.
  147.      */
  148.     private function loadExternalFiles(RouteCollection $routeCollection): void
  149.     {
  150.         if ($this->entrypointEnabled) {
  151.             $routeCollection->addCollection($this->fileLoader->load('api.xml'));
  152.         }
  153.         if ($this->docsEnabled) {
  154.             $routeCollection->addCollection($this->fileLoader->load('docs.xml'));
  155.         }
  156.         if ($this->graphqlEnabled) {
  157.             $graphqlCollection $this->fileLoader->load('graphql/graphql.xml');
  158.             $graphqlCollection->addDefaults(['_graphql' => true]);
  159.             $routeCollection->addCollection($graphqlCollection);
  160.         }
  161.         if ($this->graphiQlEnabled) {
  162.             $graphiQlCollection $this->fileLoader->load('graphql/graphiql.xml');
  163.             $graphiQlCollection->addDefaults(['_graphql' => true]);
  164.             $routeCollection->addCollection($graphiQlCollection);
  165.         }
  166.         if ($this->graphQlPlaygroundEnabled) {
  167.             $graphQlPlaygroundCollection $this->fileLoader->load('graphql/graphql_playground.xml');
  168.             $graphQlPlaygroundCollection->addDefaults(['_graphql' => true]);
  169.             $routeCollection->addCollection($graphQlPlaygroundCollection);
  170.         }
  171.         if (isset($this->formats['jsonld'])) {
  172.             $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
  173.         }
  174.     }
  175.     /**
  176.      * Creates and adds a route for the given operation to the route collection.
  177.      *
  178.      * @throws RuntimeException
  179.      */
  180.     private function addRoute(RouteCollection $routeCollectionstring $resourceClassstring $operationName, array $operationResourceMetadata $resourceMetadatastring $operationType): void
  181.     {
  182.         $resourceShortName $resourceMetadata->getShortName();
  183.         if (isset($operation['route_name'])) {
  184.             if (!isset($operation['method'])) {
  185.                 @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);
  186.             }
  187.             return;
  188.         }
  189.         if (!isset($operation['method'])) {
  190.             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));
  191.         }
  192.         if (null === $controller $operation['controller'] ?? null) {
  193.             $controller sprintf('%s%s_%s'self::DEFAULT_ACTION_PATTERNstrtolower($operation['method']), $operationType);
  194.             if (!$this->container->has($controller)) {
  195.                 throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.'$operationType$operation['method']));
  196.             }
  197.         }
  198.         if ($resourceMetadata->getItemOperations()) {
  199.             $operation['identifiers'] = (array) ($operation['identifiers'] ?? $resourceMetadata->getAttribute('identifiers'$this->identifiersExtractor $this->identifiersExtractor->getIdentifiersFromResourceClass($resourceClass) : ['id']));
  200.         } else {
  201.             $operation['identifiers'] = $operation['identifiers'] ?? [];
  202.         }
  203.         $operation['has_composite_identifier'] = \count($operation['identifiers']) > $resourceMetadata->getAttribute('composite_identifier'true) : false;
  204.         $path trim(trim($resourceMetadata->getAttribute('route_prefix''')), '/');
  205.         $path .= $this->operationPathResolver->resolveOperationPath($resourceShortName$operation$operationType$operationName);
  206.         $route = new Route(
  207.             $path,
  208.             [
  209.                 '_controller' => $controller,
  210.                 '_format' => null,
  211.                 '_stateless' => $operation['stateless'],
  212.                 '_api_resource_class' => $resourceClass,
  213.                 '_api_identifiers' => $operation['identifiers'],
  214.                 '_api_has_composite_identifier' => $operation['has_composite_identifier'],
  215.                 sprintf('_api_%s_operation_name'$operationType) => $operationName,
  216.             ] + ($operation['defaults'] ?? []),
  217.             $operation['requirements'] ?? [],
  218.             $operation['options'] ?? [],
  219.             $operation['host'] ?? '',
  220.             $operation['schemes'] ?? [],
  221.             [$operation['method']],
  222.             $operation['condition'] ?? ''
  223.         );
  224.         $routeCollection->add(RouteNameGenerator::generate($operationName$resourceShortName$operationType), $route);
  225.     }
  226. }