Completed
Push — master ( f73309...4d4b19 )
by Antoine
03:25
created

ApiLoader::computeSubresourceOperations()   C

Complexity

Conditions 8
Paths 13

Size

Total Lines 67
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 67
rs 6.6523
c 0
b 0
f 0
cc 8
eloc 41
nc 13
nop 4

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