Passed
Pull Request — 2.4 (#2481)
by Ben
04:17 queued 01:14
created

ApiLoader::addRoute()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 53
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 35
nc 7
nop 6
dl 0
loc 53
rs 8.7377
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        /** @var string[]|string $paths */
61
        $paths = $kernel->locateResource('@ApiPlatformBundle/Resources/config/routing');
62
        $this->fileLoader = new XmlFileLoader(new FileLocator($paths));
63
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
64
        $this->resourceMetadataFactory = $resourceMetadataFactory;
65
        $this->operationPathResolver = $operationPathResolver;
66
        $this->container = $container;
67
        $this->formats = $formats;
68
        $this->resourceClassDirectories = $resourceClassDirectories;
69
        $this->subresourceOperationFactory = $subresourceOperationFactory;
70
        $this->graphqlEnabled = $graphqlEnabled;
71
        $this->entrypointEnabled = $entrypointEnabled;
72
        $this->docsEnabled = $docsEnabled;
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    public function load($data, $type = null): RouteCollection
79
    {
80
        $routeCollection = new RouteCollection();
81
        foreach ($this->resourceClassDirectories as $directory) {
82
            $routeCollection->addResource(new DirectoryResource($directory, '/\.php$/'));
83
        }
84
85
        $this->loadExternalFiles($routeCollection);
86
87
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
88
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
89
            $resourceShortName = $resourceMetadata->getShortName();
90
91
            if (null === $resourceShortName) {
92
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
93
            }
94
95
            if (null !== $collectionOperations = $resourceMetadata->getCollectionOperations()) {
96
                foreach ($collectionOperations as $operationName => $operation) {
97
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceMetadata, OperationType::COLLECTION);
98
                }
99
            }
100
101
            if (null !== $itemOperations = $resourceMetadata->getItemOperations()) {
102
                foreach ($itemOperations as $operationName => $operation) {
103
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceMetadata, OperationType::ITEM);
104
                }
105
            }
106
107
            if (null === $this->subresourceOperationFactory) {
108
                continue;
109
            }
110
111
            foreach ($this->subresourceOperationFactory->create($resourceClass) as $operationId => $operation) {
112
                if (null === $controller = $operation['controller'] ?? null) {
113
                    $controller = self::DEFAULT_ACTION_PATTERN.'get_subresource';
114
115
                    if (!$this->container->has($controller)) {
116
                        throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', OperationType::SUBRESOURCE, 'GET'));
117
                    }
118
                }
119
120
                $routeCollection->add($operation['route_name'], new Route(
121
                    $operation['path'],
122
                    [
123
                        '_controller' => $controller,
124
                        '_format' => null,
125
                        '_api_resource_class' => $operation['resource_class'],
126
                        '_api_input_class' => $operation['input_class'],
127
                        '_api_output_class' => $operation['output_class'],
128
                        '_api_subresource_operation_name' => $operation['route_name'],
129
                        '_api_subresource_context' => [
130
                            'property' => $operation['property'],
131
                            'identifiers' => $operation['identifiers'],
132
                            'collection' => $operation['collection'],
133
                            'operationId' => $operationId,
134
                        ],
135
                    ] + ($operation['defaults'] ?? []),
136
                    $operation['requirements'] ?? [],
137
                    $operation['options'] ?? [],
138
                    $operation['host'] ?? '',
139
                    $operation['schemes'] ?? [],
140
                    ['GET'],
141
                    $operation['condition'] ?? ''
142
                ));
143
            }
144
        }
145
146
        return $routeCollection;
147
    }
148
149
    /**
150
     * {@inheritdoc}
151
     */
152
    public function supports($resource, $type = null)
153
    {
154
        return 'api_platform' === $type;
155
    }
156
157
    /**
158
     * Load external files.
159
     */
160
    private function loadExternalFiles(RouteCollection $routeCollection)
161
    {
162
        if ($this->entrypointEnabled) {
163
            $routeCollection->addCollection($this->fileLoader->load('api.xml'));
164
        }
165
166
        if ($this->docsEnabled) {
167
            $routeCollection->addCollection($this->fileLoader->load('docs.xml'));
168
        }
169
170
        if ($this->graphqlEnabled) {
171
            $graphqlCollection = $this->fileLoader->load('graphql.xml');
172
            $graphqlCollection->addDefaults(['_graphql' => true]);
173
            $routeCollection->addCollection($graphqlCollection);
174
        }
175
176
        if (isset($this->formats['jsonld'])) {
177
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
178
        }
179
    }
180
181
    /**
182
     * Creates and adds a route for the given operation to the route collection.
183
     *
184
     * @throws RuntimeException
185
     */
186
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, ResourceMetadata $resourceMetadata, string $operationType)
187
    {
188
        $resourceShortName = $resourceMetadata->getShortName();
189
190
        if (isset($operation['route_name'])) {
191
            return;
192
        }
193
194
        if (!isset($operation['method'])) {
195
            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));
196
        }
197
198
        if (null === $controller = $operation['controller'] ?? null) {
199
            $controller = sprintf('%s%s_%s', self::DEFAULT_ACTION_PATTERN, strtolower($operation['method']), $operationType);
200
201
            if (!$this->container->has($controller)) {
202
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
203
            }
204
        }
205
206
        $path = trim(trim($resourceMetadata->getAttribute('route_prefix', '')), '/');
207
        $path .= $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType, $operationName);
0 ignored issues
show
Bug introduced by
It seems like $resourceShortName can also be of type null; however, parameter $resourceShortName of ApiPlatform\Core\PathRes...:resolveOperationPath() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

207
        $path .= $this->operationPathResolver->resolveOperationPath(/** @scrutinizer ignore-type */ $resourceShortName, $operation, $operationType, $operationName);
Loading history...
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

207
        $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...
208
209
        $inputClass = $resourceMetadata->getAttribute('input_class', $resourceClass);
210
        $outputClass = $resourceMetadata->getAttribute('output_class', $resourceClass);
211
212
        if (OperationType::ITEM === $operationType) {
213
            $inputClass = $resourceMetadata->getItemOperationAttribute($operationName, 'input_class', $inputClass);
214
            $outputClass = $resourceMetadata->getItemOperationAttribute($operationName, 'output_class', $outputClass);
215
        } else {
216
            $inputClass = $resourceMetadata->getCollectionOperationAttribute($operationName, 'input_class', $inputClass);
217
            $outputClass = $resourceMetadata->getCollectionOperationAttribute($operationName, 'output_class', $outputClass);
218
        }
219
220
        $route = new Route(
221
            $path,
222
            [
223
                '_controller' => $controller,
224
                '_format' => null,
225
                '_api_resource_class' => $resourceClass,
226
                '_api_input_class' => $inputClass,
227
                '_api_output_class' => $outputClass,
228
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
229
            ] + ($operation['defaults'] ?? []),
230
            $operation['requirements'] ?? [],
231
            $operation['options'] ?? [],
232
            $operation['host'] ?? '',
233
            $operation['schemes'] ?? [],
234
            [$operation['method']],
235
            $operation['condition'] ?? ''
236
        );
237
238
        $routeCollection->add(RouteNameGenerator::generate($operationName, $resourceShortName, $operationType), $route);
0 ignored issues
show
Bug introduced by
It seems like $resourceShortName can also be of type null; however, parameter $resourceShortName of ApiPlatform\Core\Bridge\...meGenerator::generate() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

238
        $routeCollection->add(RouteNameGenerator::generate($operationName, /** @scrutinizer ignore-type */ $resourceShortName, $operationType), $route);
Loading history...
239
    }
240
}
241