Completed
Pull Request — 2.0 (#1192)
by
unknown
03:00
created

ApiLoader   C

Complexity

Total Complexity 28

Size/Duplication

Total Lines 238
Duplicated Lines 4.2 %

Coupling/Cohesion

Components 1
Dependencies 19

Importance

Changes 0
Metric Value
wmc 28
lcom 1
cbo 19
dl 10
loc 238
rs 6.875
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
C load() 10 34 8
A routeNameResolver() 0 6 2
C computeSubresourceOperations() 0 75 9
A supports() 0 4 1
A loadExternalFiles() 0 8 2
B addRoute() 0 35 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\Property\Factory\PropertyMetadataFactoryInterface;
20
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
21
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
22
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
23
use ApiPlatform\Core\PathResolver\OperationPathResolverInterface;
24
use Doctrine\Common\Inflector\Inflector;
25
use Symfony\Component\Config\FileLocator;
26
use Symfony\Component\Config\Loader\Loader;
27
use Symfony\Component\Config\Resource\DirectoryResource;
28
use Symfony\Component\DependencyInjection\ContainerInterface;
29
use Symfony\Component\HttpKernel\KernelInterface;
30
use Symfony\Component\Routing\Loader\XmlFileLoader;
31
use Symfony\Component\Routing\Route;
32
use Symfony\Component\Routing\RouteCollection;
33
34
/**
35
 * Loads Resources.
36
 *
37
 * @author Kévin Dunglas <[email protected]>
38
 */
39
final class ApiLoader extends Loader
40
{
41
    /**
42
     * @deprecated since version 2.1, to be removed in 3.0. Use {@see RouteNameGenerator::ROUTE_NAME_PREFIX} instead.
43
     */
44
    const ROUTE_NAME_PREFIX = 'api_';
45
    const DEFAULT_ACTION_PATTERN = 'api_platform.action.';
46
    const SUBRESOURCE_SUFFIX = '_get_subresource';
47
48
    private $fileLoader;
49
    private $propertyNameCollectionFactory;
50
    private $propertyMetadataFactory;
51
    private $resourceNameCollectionFactory;
52
    private $resourceMetadataFactory;
53
    private $operationPathResolver;
54
    private $container;
55
    private $formats;
56
    private $resourceClassDirectories;
57
58
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, OperationPathResolverInterface $operationPathResolver, ContainerInterface $container, array $formats, array $resourceClassDirectories = [], PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory = null, PropertyMetadataFactoryInterface $propertyMetadataFactory = null)
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->propertyNameCollectionFactory = $propertyNameCollectionFactory;
68
        $this->propertyMetadataFactory = $propertyMetadataFactory;
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function load($data, $type = null): RouteCollection
75
    {
76
        $routeCollection = new RouteCollection();
77
        foreach ($this->resourceClassDirectories as $directory) {
78
            $routeCollection->addResource(new DirectoryResource($directory, '/\.php$/'));
79
        }
80
81
        $this->loadExternalFiles($routeCollection);
82
83
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
84
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
85
            $resourceShortName = $resourceMetadata->getShortName();
86
87
            if (null === $resourceShortName) {
88
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
89
            }
90
91 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...
92
                foreach ($collectionOperations as $operationName => $operation) {
93
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationType::COLLECTION);
94
                }
95
            }
96
97 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...
98
                foreach ($itemOperations as $operationName => $operation) {
99
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationType::ITEM);
100
                }
101
            }
102
103
            $this->computeSubresourceOperations($routeCollection, $resourceClass);
104
        }
105
106
        return $routeCollection;
107
    }
108
109
    /**
110
     * Transforms a given string to a tableized, pluralized string.
111
     *
112
     * @param string $name usually a ResourceMetadata shortname
113
     *
114
     * @return string A string that is a part of the route name
115
     */
116
    private function routeNameResolver(string $name, bool $pluralize = true): string
117
    {
118
        $name = Inflector::tableize($name);
119
120
        return $pluralize ? Inflector::pluralize($name) : $name;
121
    }
122
123
    /**
124
     * Handles subresource operations recursively and declare their corresponding routes.
125
     *
126
     * @param RouteCollection $routeCollection
127
     * @param string          $resourceClass
128
     * @param string          $rootResourceClass null on the first iteration, it then keeps track of the origin resource class
129
     * @param array           $parentOperation   the previous call operation
130
     */
131
    private function computeSubresourceOperations(RouteCollection $routeCollection, string $resourceClass, string $rootResourceClass = null, array $parentOperation = null, array $visited = [])
132
    {
133
        if (null === $this->propertyNameCollectionFactory || null === $this->propertyMetadataFactory) {
134
            return;
135
        }
136
137
        if (null === $rootResourceClass) {
138
            $rootResourceClass = $resourceClass;
139
        }
140
141
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $property) {
142
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $property);
143
144
            if (null === $propertyMetadata->hasSubresource()) {
145
                continue;
146
            }
147
148
            $isCollection = $propertyMetadata->getType()->isCollection();
149
            $subresource = $isCollection ? $propertyMetadata->getType()->getCollectionValueType()->getClassName() : $propertyMetadata->getType()->getClassName();
150
151
            $propertyName = $this->routeNameResolver($property, $isCollection);
152
153
            $operation = [
154
                'property' => $property,
155
                'collection' => $isCollection,
156
            ];
157
158
            $visiting = "$rootResourceClass $resourceClass $propertyName $subresource";
159
160
            if (in_array($visiting, $visited, true)) {
161
                continue;
162
            }
163
164
            $visited[] = $visiting;
165
166
            if (null === $parentOperation) {
167
                $rootResourceMetadata = $this->resourceMetadataFactory->create($rootResourceClass);
168
                $rootShortname = $rootResourceMetadata->getShortName();
169
                $resourceRouteName = $this->routeNameResolver($rootShortname);
170
171
                $operation['identifiers'] = [['id', $rootResourceClass]];
172
                $operation['route_name'] = sprintf('%s%s_%s%s', RouteNameGenerator::ROUTE_NAME_PREFIX, $resourceRouteName, $propertyName, self::SUBRESOURCE_SUFFIX);
173
                $operation['path'] = $this->operationPathResolver->resolveOperationPath($rootShortname, $operation, OperationType::SUBRESOURCE, $operation['route_name']);
0 ignored issues
show
Unused Code introduced by
The call to OperationPathResolverInt...:resolveOperationPath() has too many arguments starting with $operation['route_name'].

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...
174
            } else {
175
                $operation['identifiers'] = $parentOperation['identifiers'];
176
                $operation['identifiers'][] = [$parentOperation['property'], $resourceClass];
177
                $operation['route_name'] = str_replace(self::SUBRESOURCE_SUFFIX, "_$propertyName".self::SUBRESOURCE_SUFFIX, $parentOperation['route_name']);
178
                $operation['path'] = $this->operationPathResolver->resolveOperationPath($parentOperation['path'], $operation, OperationType::SUBRESOURCE, $operation['route_name']);
0 ignored issues
show
Unused Code introduced by
The call to OperationPathResolverInt...:resolveOperationPath() has too many arguments starting with $operation['route_name'].

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...
179
            }
180
181
            $route = new Route(
182
                $operation['path'],
183
                [
184
                    '_controller' => self::DEFAULT_ACTION_PATTERN.'get_subresource',
185
                    '_format' => null,
186
                    '_api_resource_class' => $subresource,
187
                    '_api_subresource_operation_name' => $operation['route_name'],
188
                    '_api_subresource_context' => [
189
                        'property' => $operation['property'],
190
                        'identifiers' => $operation['identifiers'],
191
                        'collection' => $isCollection,
192
                    ],
193
                ],
194
                [],
195
                [],
196
                '',
197
                [],
198
                ['GET']
199
            );
200
201
            $routeCollection->add($operation['route_name'], $route);
202
203
            $this->computeSubresourceOperations($routeCollection, $subresource, $rootResourceClass, $operation, $visited);
204
        }
205
    }
206
207
    /**
208
     * {@inheritdoc}
209
     */
210
    public function supports($resource, $type = null)
211
    {
212
        return 'api_platform' === $type;
213
    }
214
215
    /**
216
     * Load external files.
217
     *
218
     * @param RouteCollection $routeCollection
219
     */
220
    private function loadExternalFiles(RouteCollection $routeCollection)
221
    {
222
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
223
224
        if (isset($this->formats['jsonld'])) {
225
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
226
        }
227
    }
228
229
    /**
230
     * Creates and adds a route for the given operation to the route collection.
231
     *
232
     * @param RouteCollection $routeCollection
233
     * @param string          $resourceClass
234
     * @param string          $operationName
235
     * @param array           $operation
236
     * @param string          $resourceShortName
237
     * @param string          $operationType
238
     *
239
     * @throws RuntimeException
240
     */
241
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, string $operationType)
242
    {
243
        if (isset($operation['route_name'])) {
244
            return;
245
        }
246
247
        if (!isset($operation['method'])) {
248
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
249
        }
250
251
        if (null === $controller = $operation['controller'] ?? null) {
252
            $controller = sprintf('%s%s_%s', self::DEFAULT_ACTION_PATTERN, strtolower($operation['method']), $operationType);
253
254
            if (!$this->container->has($controller)) {
255
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
256
            }
257
        }
258
259
        $route = new Route(
260
            $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...
261
            [
262
                '_controller' => $controller,
263
                '_format' => null,
264
                '_api_resource_class' => $resourceClass,
265
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
266
            ],
267
            [],
268
            [],
269
            '',
270
            [],
271
            [$operation['method']]
272
        );
273
274
        $routeCollection->add(RouteNameGenerator::generate($operationName, $resourceShortName, $operationType), $route);
275
    }
276
}
277