Completed
Pull Request — master (#904)
by Antoine
03:26
created

ApiLoader   B

Complexity

Total Complexity 23

Size/Duplication

Total Lines 217
Duplicated Lines 4.61 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 17
dl 10
loc 217
rs 7.8571
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
C load() 10 31 7
A supports() 0 4 1
A loadExternalFiles() 0 8 2
B addRoute() 0 47 6
B computeSubcollectionOperations() 0 64 6

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
namespace ApiPlatform\Core\Bridge\Symfony\Routing;
13
14
use ApiPlatform\Core\Exception\InvalidResourceException;
15
use ApiPlatform\Core\Exception\RuntimeException;
16
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
17
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
18
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
19
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
20
use ApiPlatform\Core\PathResolver\OperationPathResolverInterface;
21
use ApiPlatform\Core\Util\OperationTypes;
22
use Doctrine\Common\Inflector\Inflector;
23
use Symfony\Component\Config\FileLocator;
24
use Symfony\Component\Config\Loader\Loader;
25
use Symfony\Component\DependencyInjection\ContainerInterface;
26
use Symfony\Component\HttpKernel\KernelInterface;
27
use Symfony\Component\Routing\Loader\XmlFileLoader;
28
use Symfony\Component\Routing\Route;
29
use Symfony\Component\Routing\RouteCollection;
30
31
/**
32
 * Loads Resources.
33
 *
34
 * @author Kévin Dunglas <[email protected]>
35
 */
36
final class ApiLoader extends Loader
37
{
38
    const ROUTE_NAME_PREFIX = 'api_';
39
    const DEFAULT_ACTION_PATTERN = 'api_platform.action.';
40
    const SUBCOLLECTION_SUFFIX = '_get_subcollection';
41
42
    private $fileLoader;
43
    private $propertyNameCollectionFactory;
44
    private $propertyMetadataFactory;
45
    private $resourceNameCollectionFactory;
46
    private $resourceMetadataFactory;
47
    private $operationPathResolver;
48
    private $container;
49
    private $formats;
50
51
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, OperationPathResolverInterface $operationPathResolver, ContainerInterface $container, array $formats)
52
    {
53
        $this->fileLoader = new XmlFileLoader(new FileLocator($kernel->locateResource('@ApiPlatformBundle/Resources/config/routing')));
54
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
55
        $this->resourceMetadataFactory = $resourceMetadataFactory;
56
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
57
        $this->propertyMetadataFactory = $propertyMetadataFactory;
58
        $this->operationPathResolver = $operationPathResolver;
59
        $this->container = $container;
60
        $this->formats = $formats;
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public function load($data, $type = null)
67
    {
68
        $routeCollection = new RouteCollection();
69
70
        $this->loadExternalFiles($routeCollection);
71
72
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
73
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
74
            $resourceShortName = $resourceMetadata->getShortName();
75
76
            if (null === $resourceShortName) {
77
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
78
            }
79
80 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...
81
                foreach ($collectionOperations as $operationName => $operation) {
82
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationTypes::COLLECTION);
83
                }
84
            }
85
86 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...
87
                foreach ($itemOperations as $operationName => $operation) {
88
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationTypes::ITEM);
89
                }
90
            }
91
92
            $this->computeSubcollectionOperations($routeCollection, $resourceClass);
93
        }
94
95
        return $routeCollection;
96
    }
97
98
    /**
99
     * Handles subcollection operations recursively and declare their corresponding routes.
100
     *
101
     * @param RouteCollection $routeCollection
102
     * @param string          $resourceClass
103
     * @param string          $rootResourceClass null on the first iteration, it then keeps track of the origin resource class
104
     * @param string          $rootResourceClass null on the first iteration, it then keeps track of the parent operation
105
     */
106
    private function computeSubcollectionOperations(RouteCollection $routeCollection, string $resourceClass, $rootResourceClass = null, $parentOperation = null)
107
    {
108
        if (null === $rootResourceClass) {
109
            $rootResourceClass = $resourceClass;
110
        }
111
112
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $property) {
113
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $property);
114
115
            if (!$propertyMetadata->hasSubcollection()) {
116
                continue;
117
            }
118
119
            $subcollection = $propertyMetadata->getType()->isCollection() ? $propertyMetadata->getType()->getCollectionValueType()->getClassName() : $propertyMetadata->getType()->getClassName();
120
121
            $propertyName = Inflector::pluralize(Inflector::tableize($property));
122
123
            $operation = [
124
                'property' => $property,
125
            ];
126
127
            if (null === $parentOperation) {
128
                $rootResourceMetadata = $this->resourceMetadataFactory->create($rootResourceClass);
129
                $rootShortname = $rootResourceMetadata->getShortName();
130
                $resourceRouteName = Inflector::pluralize(Inflector::tableize($rootShortname));
131
132
                $operation['identifiers'] = [['id', $rootResourceClass]];
133
                $operation['route_name'] = sprintf('%s%s_%s%s', self::ROUTE_NAME_PREFIX, $resourceRouteName, $propertyName, self::SUBCOLLECTION_SUFFIX);
134
135
                $operation['path'] = $this->operationPathResolver->resolveOperationPath($rootShortname, $operation, OperationTypes::SUBCOLLECTION);
136
            } else {
137
                $identifier = $parentOperation['property'];
138
139
                $operation['identifiers'] = $parentOperation['identifiers'];
140
                $operation['identifiers'][] = [$identifier, $resourceClass];
141
                $operation['route_name'] = str_replace(self::SUBCOLLECTION_SUFFIX, "_$propertyName".self::SUBCOLLECTION_SUFFIX, $parentOperation['route_name']);
142
143
                $operation['path'] = $this->operationPathResolver->resolveOperationPath($parentOperation['path'], $operation, OperationTypes::SUBCOLLECTION);
144
            }
145
146
            $route = new Route(
147
                $operation['path'],
148
                [
149
                    '_controller' => self::DEFAULT_ACTION_PATTERN.'get_subcollection',
150
                    '_format' => null,
151
                    '_api_resource_class' => $subcollection,
152
                    '_api_subcollection_operation_name' => 'get',
153
                    '_api_subcollection_context' => [
154
                        'property' => $operation['property'],
155
                        'identifiers' => $operation['identifiers'],
156
                    ],
157
                ],
158
                [],
159
                [],
160
                '',
161
                [],
162
                ['GET']
163
            );
164
165
            $routeCollection->add($operation['route_name'], $route);
166
167
            $this->computeSubcollectionOperations($routeCollection, $subcollection, $rootResourceClass, $operation);
168
        }
169
    }
170
171
    /**
172
     * {@inheritdoc}
173
     */
174
    public function supports($resource, $type = null)
175
    {
176
        return 'api_platform' === $type;
177
    }
178
179
    /**
180
     * Load external files.
181
     *
182
     * @param RouteCollection $routeCollection
183
     */
184
    private function loadExternalFiles(RouteCollection $routeCollection)
185
    {
186
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
187
188
        if (isset($this->formats['jsonld'])) {
189
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
190
        }
191
    }
192
193
    /**
194
     * Creates and adds a route for the given operation to the route collection.
195
     *
196
     * @param RouteCollection $routeCollection
197
     * @param string          $resourceClass
198
     * @param string          $operationName
199
     * @param array           $operation
200
     * @param string          $resourceShortName
201
     * @param bool            $collection
0 ignored issues
show
Documentation introduced by
There is no parameter named $collection. Did you maybe mean $routeCollection?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
202
     *
203
     * @throws RuntimeException
204
     */
205
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, string $operationType)
206
    {
207
        if (isset($operation['route_name'])) {
208
            return;
209
        }
210
211
        if (!isset($operation['method'])) {
212
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
213
        }
214
215
        $controller = $operation['controller'] ?? null;
216
        $actionName = sprintf('%s_%s', strtolower($operation['method']), $operationType);
217
218
        if (null === $controller) {
219
            $controller = self::DEFAULT_ACTION_PATTERN.$actionName;
220
221
            if (!$this->container->has($controller)) {
222
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
223
            }
224
        }
225
226
        if ($operationName !== strtolower($operation['method'])) {
227
            $actionName = sprintf('%s_%s', $operationName, $operationType);
228
        }
229
230
        $path = $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType);
231
232
        $resourceRouteName = Inflector::pluralize(Inflector::tableize($resourceShortName));
233
        $routeName = sprintf('%s%s_%s', self::ROUTE_NAME_PREFIX, $resourceRouteName, $actionName);
234
235
        $route = new Route(
236
            $path,
237
            [
238
                '_controller' => $controller,
239
                '_format' => null,
240
                '_api_resource_class' => $resourceClass,
241
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
242
            ],
243
            [],
244
            [],
245
            '',
246
            [],
247
            [$operation['method']]
248
        );
249
250
        $routeCollection->add($routeName, $route);
251
    }
252
}
253