Completed
Push — master ( 0136f1...4ea214 )
by Kévin
16s queued 11s
created

ApiLoader::loadExternalFiles()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.6737
c 0
b 0
f 0
cc 5
eloc 12
nc 16
nop 1
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Bridge\Symfony\Routing;
15
16
use ApiPlatform\Core\Api\OperationType;
17
use ApiPlatform\Core\Exception\InvalidResourceException;
18
use ApiPlatform\Core\Exception\RuntimeException;
19
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
20
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
21
use ApiPlatform\Core\Operation\Factory\SubresourceOperationFactoryInterface;
22
use ApiPlatform\Core\PathResolver\OperationPathResolverInterface;
23
use Symfony\Component\Config\FileLocator;
24
use Symfony\Component\Config\Loader\Loader;
25
use Symfony\Component\Config\Resource\DirectoryResource;
26
use Symfony\Component\DependencyInjection\ContainerInterface;
27
use Symfony\Component\HttpKernel\KernelInterface;
28
use Symfony\Component\Routing\Loader\XmlFileLoader;
29
use Symfony\Component\Routing\Route;
30
use Symfony\Component\Routing\RouteCollection;
31
32
/**
33
 * Loads Resources.
34
 *
35
 * @author Kévin Dunglas <[email protected]>
36
 */
37
final class ApiLoader extends Loader
38
{
39
    /**
40
     * @deprecated since version 2.1, to be removed in 3.0. Use {@see RouteNameGenerator::ROUTE_NAME_PREFIX} instead.
41
     */
42
    const ROUTE_NAME_PREFIX = 'api_';
43
    const DEFAULT_ACTION_PATTERN = 'api_platform.action.';
44
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 $entrypointEnabled;
55
    private $docsEnabled;
56
57
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, OperationPathResolverInterface $operationPathResolver, ContainerInterface $container, array $formats, array $resourceClassDirectories = [], SubresourceOperationFactoryInterface $subresourceOperationFactory = null, bool $graphqlEnabled = false, bool $entrypointEnabled = true, bool $docsEnabled = true)
58
    {
59
        $this->fileLoader = new XmlFileLoader(new FileLocator($kernel->locateResource('@ApiPlatformBundle/Resources/config/routing')));
0 ignored issues
show
Bug introduced by
It seems like $kernel->locateResource(...ources/config/routing') targeting Symfony\Component\HttpKe...rface::locateResource() can also be of type array; however, Symfony\Component\Config...eLocator::__construct() does only seem to accept string|array<integer,string>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
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->entrypointEnabled = $entrypointEnabled;
69
        $this->docsEnabled = $docsEnabled;
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function load($data, $type = null): RouteCollection
76
    {
77
        $routeCollection = new RouteCollection();
78
        foreach ($this->resourceClassDirectories as $directory) {
79
            $routeCollection->addResource(new DirectoryResource($directory, '/\.php$/'));
80
        }
81
82
        $this->loadExternalFiles($routeCollection);
83
84
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
85
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
86
            $resourceShortName = $resourceMetadata->getShortName();
87
88
            if (null === $resourceShortName) {
89
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
90
            }
91
92 View Code Duplication
            if (null !== $collectionOperations = $resourceMetadata->getCollectionOperations()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
93
                foreach ($collectionOperations as $operationName => $operation) {
94
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationType::COLLECTION);
95
                }
96
            }
97
98 View Code Duplication
            if (null !== $itemOperations = $resourceMetadata->getItemOperations()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
99
                foreach ($itemOperations as $operationName => $operation) {
100
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationType::ITEM);
101
                }
102
            }
103
104
            if (null === $this->subresourceOperationFactory) {
105
                continue;
106
            }
107
108
            foreach ($this->subresourceOperationFactory->create($resourceClass) as $operationId => $operation) {
109
                $routeCollection->add($operation['route_name'], new Route(
110
                    $operation['path'],
111
                    [
112
                        '_controller' => self::DEFAULT_ACTION_PATTERN.'get_subresource',
113
                        '_format' => null,
114
                        '_api_resource_class' => $operation['resource_class'],
115
                        '_api_subresource_operation_name' => $operation['route_name'],
116
                        '_api_subresource_context' => [
117
                            'property' => $operation['property'],
118
                            'identifiers' => $operation['identifiers'],
119
                            'collection' => $operation['collection'],
120
                            'operationId' => $operationId,
121
                        ],
122
                    ] + $operation['defaults'] ?? [],
123
                    $operation['requirements'] ?? [],
124
                    $operation['options'] ?? [],
125
                    $operation['host'] ?? '',
126
                    $operation['schemes'] ?? [],
127
                    ['GET'],
128
                    $operation['condition'] ?? ''
129
                ));
130
            }
131
        }
132
133
        return $routeCollection;
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139
    public function supports($resource, $type = null)
140
    {
141
        return 'api_platform' === $type;
142
    }
143
144
    /**
145
     * Load external files.
146
     *
147
     * @param RouteCollection $routeCollection
148
     */
149
    private function loadExternalFiles(RouteCollection $routeCollection)
150
    {
151
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
152
153
        if ($this->entrypointEnabled) {
154
            $routeCollection->addCollection($this->fileLoader->load('api.xml'));
155
        }
156
157
        if ($this->docsEnabled) {
158
            $routeCollection->addCollection($this->fileLoader->load('docs.xml'));
159
        }
160
161
        if ($this->graphqlEnabled) {
162
            $graphqlCollection = $this->fileLoader->load('graphql.xml');
163
            $graphqlCollection->addDefaults(['_graphql' => true]);
164
            $routeCollection->addCollection($graphqlCollection);
165
        }
166
167
        if (isset($this->formats['jsonld'])) {
168
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
169
        }
170
    }
171
172
    /**
173
     * Creates and adds a route for the given operation to the route collection.
174
     *
175
     * @param RouteCollection $routeCollection
176
     * @param string          $resourceClass
177
     * @param string          $operationName
178
     * @param array           $operation
179
     * @param string          $resourceShortName
180
     * @param string          $operationType
181
     *
182
     * @throws RuntimeException
183
     */
184
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, string $operationType)
185
    {
186
        if (isset($operation['route_name'])) {
187
            return;
188
        }
189
190
        if (!isset($operation['method'])) {
191
            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));
192
        }
193
194
        if (null === $controller = $operation['controller'] ?? null) {
195
            $controller = sprintf('%s%s_%s', self::DEFAULT_ACTION_PATTERN, strtolower($operation['method']), $operationType);
196
197
            if (!$this->container->has($controller)) {
198
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
199
            }
200
        }
201
202
        $route = new Route(
203
            $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType, $operationName),
0 ignored issues
show
Unused Code introduced by
The call to OperationPathResolverInt...:resolveOperationPath() has too many arguments starting with $operationName.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
204
            [
205
                '_controller' => $controller,
206
                '_format' => null,
207
                '_api_resource_class' => $resourceClass,
208
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
209
            ] + ($operation['defaults'] ?? []),
210
            $operation['requirements'] ?? [],
211
            $operation['options'] ?? [],
212
            $operation['host'] ?? '',
213
            $operation['schemes'] ?? [],
214
            [$operation['method']],
215
            $operation['condition'] ?? ''
216
        );
217
218
        $routeCollection->add(RouteNameGenerator::generate($operationName, $resourceShortName, $operationType), $route);
219
    }
220
}
221