Completed
Pull Request — master (#904)
by Antoine
04:35
created

ApiLoader   B

Complexity

Total Complexity 22

Size/Duplication

Total Lines 215
Duplicated Lines 4.65 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
wmc 22
lcom 1
cbo 17
dl 10
loc 215
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
B computeSubcollectionOperations() 0 62 5
A supports() 0 4 1
A loadExternalFiles() 0 8 2
B addRoute() 0 47 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 (null === $subcollection = $propertyMetadata->getSubcollection()) {
116
                continue;
117
            }
118
119
            $propertyName = Inflector::pluralize(Inflector::tableize($property));
120
121
            $operation = [
122
                'property' => $property,
123
            ];
124
125
            if (null === $parentOperation) {
126
                $rootResourceMetadata = $this->resourceMetadataFactory->create($rootResourceClass);
127
                $rootShortname = $rootResourceMetadata->getShortName();
128
                $resourceRouteName = Inflector::pluralize(Inflector::tableize($rootShortname));
129
130
                $operation['identifiers'] = [['id', $rootResourceClass]];
131
                $operation['route_name'] = sprintf('%s%s_%s%s', self::ROUTE_NAME_PREFIX, $resourceRouteName, $propertyName, self::SUBCOLLECTION_SUFFIX);
132
133
                $operation['path'] = $this->operationPathResolver->resolveOperationPath($rootShortname, $operation, OperationTypes::SUBCOLLECTION);
134
            } else {
135
                $identifier = $parentOperation['property'];
136
137
                $operation['identifiers'] = $parentOperation['identifiers'];
138
                $operation['identifiers'][] = [$identifier, $resourceClass];
139
                $operation['route_name'] = str_replace(self::SUBCOLLECTION_SUFFIX, "_$propertyName".self::SUBCOLLECTION_SUFFIX, $parentOperation['route_name']);
140
141
                $operation['path'] = $this->operationPathResolver->resolveOperationPath($parentOperation['path'], $operation, OperationTypes::SUBCOLLECTION);
142
            }
143
144
            $route = new Route(
145
                $operation['path'],
146
                [
147
                    '_controller' => self::DEFAULT_ACTION_PATTERN.'get_subcollection',
148
                    '_format' => null,
149
                    '_api_resource_class' => $subcollection,
150
                    '_api_subcollection_operation_name' => 'get',
151
                    '_api_subcollection_context' => [
152
                        'property' => $operation['property'],
153
                        'identifiers' => $operation['identifiers'],
154
                    ],
155
                ],
156
                [],
157
                [],
158
                '',
159
                [],
160
                ['GET']
161
            );
162
163
            $routeCollection->add($operation['route_name'], $route);
164
165
            $this->computeSubcollectionOperations($routeCollection, $subcollection, $rootResourceClass, $operation);
166
        }
167
    }
168
169
    /**
170
     * {@inheritdoc}
171
     */
172
    public function supports($resource, $type = null)
173
    {
174
        return 'api_platform' === $type;
175
    }
176
177
    /**
178
     * Load external files.
179
     *
180
     * @param RouteCollection $routeCollection
181
     */
182
    private function loadExternalFiles(RouteCollection $routeCollection)
183
    {
184
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
185
186
        if (isset($this->formats['jsonld'])) {
187
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
188
        }
189
    }
190
191
    /**
192
     * Creates and adds a route for the given operation to the route collection.
193
     *
194
     * @param RouteCollection $routeCollection
195
     * @param string          $resourceClass
196
     * @param string          $operationName
197
     * @param array           $operation
198
     * @param string          $resourceShortName
199
     * @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...
200
     *
201
     * @throws RuntimeException
202
     */
203
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, string $operationType)
204
    {
205
        if (isset($operation['route_name'])) {
206
            return;
207
        }
208
209
        if (!isset($operation['method'])) {
210
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
211
        }
212
213
        $controller = $operation['controller'] ?? null;
214
        $actionName = sprintf('%s_%s', strtolower($operation['method']), $operationType);
215
216
        if (null === $controller) {
217
            $controller = self::DEFAULT_ACTION_PATTERN.$actionName;
218
219
            if (!$this->container->has($controller)) {
220
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
221
            }
222
        }
223
224
        if ($operationName !== strtolower($operation['method'])) {
225
            $actionName = sprintf('%s_%s', $operationName, $operationType);
226
        }
227
228
        $path = $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType);
229
230
        $resourceRouteName = Inflector::pluralize(Inflector::tableize($resourceShortName));
231
        $routeName = sprintf('%s%s_%s', self::ROUTE_NAME_PREFIX, $resourceRouteName, $actionName);
232
233
        $route = new Route(
234
            $path,
235
            [
236
                '_controller' => $controller,
237
                '_format' => null,
238
                '_api_resource_class' => $resourceClass,
239
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
240
            ],
241
            [],
242
            [],
243
            '',
244
            [],
245
            [$operation['method']]
246
        );
247
248
        $routeCollection->add($routeName, $route);
249
    }
250
}
251