Test Failed
Branch master (ec8ced)
by Kévin
11:20
created

ApiLoader::loadExternalFiles()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 11
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')));
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
            if (null !== $collectionOperations = $resourceMetadata->getCollectionOperations()) {
93
                foreach ($collectionOperations as $operationName => $operation) {
94
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationType::COLLECTION);
95
                }
96
            }
97
98
            if (null !== $itemOperations = $resourceMetadata->getItemOperations()) {
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),
1 ignored issue
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

203
            $this->operationPathResolver->/** @scrutinizer ignore-call */ 
204
                                          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...
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