Passed
Pull Request — 2.2 (#2051)
by
unknown
03:08
created

ApiLoader::loadExternalFiles()   A

Complexity

Conditions 5
Paths 16

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.3554
c 0
b 0
f 0
cc 5
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\Metadata\Resource\ResourceMetadata;
22
use ApiPlatform\Core\Operation\Factory\SubresourceOperationFactoryInterface;
23
use ApiPlatform\Core\PathResolver\OperationPathResolverInterface;
24
use Symfony\Component\Config\FileLocator;
25
use Symfony\Component\Config\Loader\Loader;
26
use Symfony\Component\Config\Resource\DirectoryResource;
27
use Symfony\Component\DependencyInjection\ContainerInterface;
28
use Symfony\Component\HttpKernel\KernelInterface;
29
use Symfony\Component\Routing\Loader\XmlFileLoader;
30
use Symfony\Component\Routing\Route;
31
use Symfony\Component\Routing\RouteCollection;
32
33
/**
34
 * Loads Resources.
35
 *
36
 * @author Kévin Dunglas <[email protected]>
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
    const ROUTE_NAME_PREFIX = 'api_';
44
    const DEFAULT_ACTION_PATTERN = 'api_platform.action.';
45
46
    private $fileLoader;
47
    private $resourceNameCollectionFactory;
48
    private $resourceMetadataFactory;
49
    private $operationPathResolver;
50
    private $container;
51
    private $formats;
52
    private $resourceClassDirectories;
53
    private $subresourceOperationFactory;
54
    private $graphqlEnabled;
55
    private $entrypointEnabled;
56
    private $docsEnabled;
57
58
    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)
59
    {
60
        $this->fileLoader = new XmlFileLoader(new FileLocator($kernel->locateResource('@ApiPlatformBundle/Resources/config/routing')));
61
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
62
        $this->resourceMetadataFactory = $resourceMetadataFactory;
63
        $this->operationPathResolver = $operationPathResolver;
64
        $this->container = $container;
65
        $this->formats = $formats;
66
        $this->resourceClassDirectories = $resourceClassDirectories;
67
        $this->subresourceOperationFactory = $subresourceOperationFactory;
68
        $this->graphqlEnabled = $graphqlEnabled;
69
        $this->entrypointEnabled = $entrypointEnabled;
70
        $this->docsEnabled = $docsEnabled;
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    public function load($data, $type = null): RouteCollection
77
    {
78
        $routeCollection = new RouteCollection();
79
        foreach ($this->resourceClassDirectories as $directory) {
80
            $routeCollection->addResource(new DirectoryResource($directory, '/\.php$/'));
81
        }
82
83
        $this->loadExternalFiles($routeCollection);
84
85
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
86
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
87
            $resourceShortName = $resourceMetadata->getShortName();
88
89
            if (null === $resourceShortName) {
90
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
91
            }
92
93
            if (null !== $collectionOperations = $resourceMetadata->getCollectionOperations()) {
94
                foreach ($collectionOperations as $operationName => $operation) {
95
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceMetadata, OperationType::COLLECTION);
96
                }
97
            }
98
99
            if (null !== $itemOperations = $resourceMetadata->getItemOperations()) {
100
                foreach ($itemOperations as $operationName => $operation) {
101
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceMetadata, OperationType::ITEM);
102
                }
103
            }
104
105
            if (null === $this->subresourceOperationFactory) {
106
                continue;
107
            }
108
109
            foreach ($this->subresourceOperationFactory->create($resourceClass) as $operationId => $operation) {
110
                if (null === $controller = $operation['controller'] ?? null) {
111
                    $controller = self::DEFAULT_ACTION_PATTERN.'get_subresource';
112
113
                    if (!$this->container->has($controller)) {
114
                        throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', OperationType::SUBRESOURCE, 'GET'));
115
                    }
116
                }
117
118
                $routeCollection->add($operation['route_name'], new Route(
119
                    $operation['path'],
120
                    [
121
                        '_controller' => $controller,
122
                        '_format' => null,
123
                        '_api_resource_class' => $operation['resource_class'],
124
                        '_api_subresource_operation_name' => $operation['route_name'],
125
                        '_api_subresource_context' => [
126
                            'property' => $operation['property'],
127
                            'identifiers' => $operation['identifiers'],
128
                            'collection' => $operation['collection'],
129
                            'operationId' => $operationId,
130
                        ],
131
                    ] + ($operation['defaults'] ?? []),
132
                    $operation['requirements'] ?? [],
133
                    $operation['options'] ?? [],
134
                    $operation['host'] ?? '',
135
                    $operation['schemes'] ?? [],
136
                    ['GET'],
137
                    $operation['condition'] ?? ''
138
                ));
139
            }
140
        }
141
142
        return $routeCollection;
143
    }
144
145
    /**
146
     * {@inheritdoc}
147
     */
148
    public function supports($resource, $type = null)
149
    {
150
        return 'api_platform' === $type;
151
    }
152
153
    /**
154
     * Load external files.
155
     *
156
     * @param RouteCollection $routeCollection
157
     */
158
    private function loadExternalFiles(RouteCollection $routeCollection)
159
    {
160
        if ($this->entrypointEnabled) {
161
            $routeCollection->addCollection($this->fileLoader->load('api.xml'));
162
        }
163
164
        if ($this->docsEnabled) {
165
            $routeCollection->addCollection($this->fileLoader->load('docs.xml'));
166
        }
167
168
        if ($this->graphqlEnabled) {
169
            $graphqlCollection = $this->fileLoader->load('graphql.xml');
170
            $graphqlCollection->addDefaults(['_graphql' => true]);
171
            $routeCollection->addCollection($graphqlCollection);
172
        }
173
174
        if (isset($this->formats['jsonld'])) {
175
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
176
        }
177
    }
178
179
    /**
180
     * Creates and adds a route for the given operation to the route collection.
181
     *
182
     * @throws RuntimeException
183
     */
184
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, ResourceMetadata $resourceMetadata, string $operationType)
185
    {
186
        $resourceShortName = $resourceMetadata->getShortName();
187
188
        if (isset($operation['route_name'])) {
189
            return;
190
        }
191
192
        if (!isset($operation['method'])) {
193
            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));
194
        }
195
196
        if (null === $controller = $operation['controller'] ?? null) {
197
            $controller = sprintf('%s%s_%s', self::DEFAULT_ACTION_PATTERN, strtolower($operation['method']), $operationType);
198
199
            if (!$this->container->has($controller)) {
200
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
201
            }
202
        }
203
204
        $path = trim(trim($resourceMetadata->getAttribute('route_prefix', '')), '/');
205
        $path .= $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType, $operationName);
0 ignored issues
show
Unused Code introduced by
The call to ApiPlatform\Core\PathRes...:resolveOperationPath() has too many arguments starting with $operationName. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

205
        $path .= $this->operationPathResolver->/** @scrutinizer ignore-call */ resolveOperationPath($resourceShortName, $operation, $operationType, $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. Please note the @ignore annotation hint above.

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