Completed
Pull Request — master (#1225)
by Antoine
02:54
created

ApiLoader   B

Complexity

Total Complexity 25

Size/Duplication

Total Lines 220
Duplicated Lines 4.55 %

Coupling/Cohesion

Components 1
Dependencies 18

Importance

Changes 0
Metric Value
wmc 25
lcom 1
cbo 18
dl 10
loc 220
rs 7.3333
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A supports() 0 4 1
A loadExternalFiles() 0 8 2
A __construct() 0 12 1
C load() 10 34 8
C computeSubresourceOperations() 0 71 8
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 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
    const SUBRESOURCE_SUFFIX = '_get_subresource';
46
47
    private $fileLoader;
48
    private $propertyNameCollectionFactory;
49
    private $propertyMetadataFactory;
50
    private $resourceNameCollectionFactory;
51
    private $resourceMetadataFactory;
52
    private $operationPathResolver;
53
    private $container;
54
    private $formats;
55
    private $resourceClassDirectories;
56
57
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, OperationPathResolverInterface $operationPathResolver, ContainerInterface $container, array $formats, array $resourceClassDirectories = [], PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory = null, PropertyMetadataFactoryInterface $propertyMetadataFactory = null)
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->propertyNameCollectionFactory = $propertyNameCollectionFactory;
67
        $this->propertyMetadataFactory = $propertyMetadataFactory;
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function load($data, $type = null): RouteCollection
74
    {
75
        $routeCollection = new RouteCollection();
76
        foreach ($this->resourceClassDirectories as $directory) {
77
            $routeCollection->addResource(new DirectoryResource($directory, '/\.php$/'));
78
        }
79
80
        $this->loadExternalFiles($routeCollection);
81
82
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
83
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
84
            $resourceShortName = $resourceMetadata->getShortName();
85
86
            if (null === $resourceShortName) {
87
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
88
            }
89
90 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...
91
                foreach ($collectionOperations as $operationName => $operation) {
92
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationType::COLLECTION);
93
                }
94
            }
95
96 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...
97
                foreach ($itemOperations as $operationName => $operation) {
98
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationType::ITEM);
99
                }
100
            }
101
102
            $this->computeSubresourceOperations($routeCollection, $resourceClass);
103
        }
104
105
        return $routeCollection;
106
    }
107
108
    /**
109
     * Handles subresource operations recursively and declare their corresponding routes.
110
     *
111
     * @param RouteCollection $routeCollection
112
     * @param string          $resourceClass
113
     * @param string          $rootResourceClass null on the first iteration, it then keeps track of the origin resource class
114
     * @param array           $parentOperation   the previous call operation
115
     */
116
    private function computeSubresourceOperations(RouteCollection $routeCollection, string $resourceClass, string $rootResourceClass = null, array $parentOperation = null, array $visited = [])
117
    {
118
        if (null === $this->propertyNameCollectionFactory || null === $this->propertyMetadataFactory) {
119
            return;
120
        }
121
122
        if (null === $rootResourceClass) {
123
            $rootResourceClass = $resourceClass;
124
        }
125
126
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $property) {
127
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $property);
128
129
            if (!$propertyMetadata->hasSubresource()) {
130
                continue;
131
            }
132
133
            $subresource = $propertyMetadata->getSubresource();
134
135
            $operation = [
136
                'property' => $property,
137
                'collection' => $subresource->isCollection(),
138
            ];
139
140
            $visiting = "$rootResourceClass $resourceClass $property {$subresource->isCollection()} {$subresource->getResourceClass()}";
141
142
            if (in_array($visiting, $visited, true)) {
143
                continue;
144
            }
145
146
            $visited[] = $visiting;
147
148
            if (null === $parentOperation) {
149
                $rootResourceMetadata = $this->resourceMetadataFactory->create($rootResourceClass);
150
                $rootShortname = $rootResourceMetadata->getShortName();
151
152
                $operation['identifiers'] = [['id', $rootResourceClass]];
153
                $operation['route_name'] = RouteNameGenerator::generate('get', $rootShortname, OperationType::SUBRESOURCE, $property, $operation['collection']);
154
                $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...
155
            } else {
156
                $operation['identifiers'] = $parentOperation['identifiers'];
157
                $operation['identifiers'][] = [$parentOperation['property'], $resourceClass];
158
                $operation['route_name'] = str_replace('get'.RouteNameGenerator::SUBRESOURCE_SUFFIX, RouteNameGenerator::routeNameResolver($property, $operation['collection']).'_get'.RouteNameGenerator::SUBRESOURCE_SUFFIX, $parentOperation['route_name']);
159
                $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...
160
            }
161
162
            $route = new Route(
163
                $operation['path'],
164
                [
165
                    '_controller' => self::DEFAULT_ACTION_PATTERN.'get_subresource',
166
                    '_format' => null,
167
                    '_api_resource_class' => $subresource->getResourceClass(),
168
                    '_api_subresource_operation_name' => $operation['route_name'],
169
                    '_api_subresource_context' => [
170
                        'property' => $operation['property'],
171
                        'identifiers' => $operation['identifiers'],
172
                        'collection' => $subresource->isCollection(),
173
                    ],
174
                ],
175
                [],
176
                [],
177
                '',
178
                [],
179
                ['GET']
180
            );
181
182
            $routeCollection->add($operation['route_name'], $route);
183
184
            $this->computeSubresourceOperations($routeCollection, $subresource->getResourceClass(), $rootResourceClass, $operation, $visited);
185
        }
186
    }
187
188
    /**
189
     * {@inheritdoc}
190
     */
191
    public function supports($resource, $type = null)
192
    {
193
        return 'api_platform' === $type;
194
    }
195
196
    /**
197
     * Load external files.
198
     *
199
     * @param RouteCollection $routeCollection
200
     */
201
    private function loadExternalFiles(RouteCollection $routeCollection)
202
    {
203
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
204
205
        if (isset($this->formats['jsonld'])) {
206
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
207
        }
208
    }
209
210
    /**
211
     * Creates and adds a route for the given operation to the route collection.
212
     *
213
     * @param RouteCollection $routeCollection
214
     * @param string          $resourceClass
215
     * @param string          $operationName
216
     * @param array           $operation
217
     * @param string          $resourceShortName
218
     * @param string          $operationType
219
     *
220
     * @throws RuntimeException
221
     */
222
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, string $operationType)
223
    {
224
        if (isset($operation['route_name'])) {
225
            return;
226
        }
227
228
        if (!isset($operation['method'])) {
229
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
230
        }
231
232
        if (null === $controller = $operation['controller'] ?? null) {
233
            $controller = sprintf('%s%s_%s', self::DEFAULT_ACTION_PATTERN, strtolower($operation['method']), $operationType);
234
235
            if (!$this->container->has($controller)) {
236
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
237
            }
238
        }
239
240
        $route = new Route(
241
            $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...
242
            [
243
                '_controller' => $controller,
244
                '_format' => null,
245
                '_api_resource_class' => $resourceClass,
246
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
247
            ],
248
            [],
249
            [],
250
            '',
251
            [],
252
            [$operation['method']]
253
        );
254
255
        $routeCollection->add(RouteNameGenerator::generate($operationName, $resourceShortName, $operationType), $route);
256
    }
257
}
258