Completed
Pull Request — master (#1144)
by Antoine
03:46
created

ApiLoader::load()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 34
Code Lines 18

Duplication

Lines 10
Ratio 29.41 %

Importance

Changes 0
Metric Value
dl 10
loc 34
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 18
nc 12
nop 2
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
                if ($this->isRecursiveSubresource($subresource, $parentOperation)) {
165
                    throw new RuntimeException("Recursive subresource declaration on the \"$property\" property of the \"$resourceClass\" class detected.");
166
                }
167
168
                $operation['identifiers'] = $parentOperation['identifiers'];
169
                $operation['identifiers'][] = [$parentOperation['property'], $resourceClass];
170
                $operation['route_name'] = str_replace(self::SUBRESOURCE_SUFFIX, "_$propertyName".self::SUBRESOURCE_SUFFIX, $parentOperation['route_name']);
171
                $operation['path'] = $this->operationPathResolver->resolveOperationPath($parentOperation['path'], $operation, OperationType::SUBRESOURCE);
172
            }
173
174
            $route = new Route(
175
                $operation['path'],
176
                [
177
                    '_controller' => self::DEFAULT_ACTION_PATTERN.'get_subresource',
178
                    '_format' => null,
179
                    '_api_resource_class' => $subresource,
180
                    '_api_subresource_operation_name' => $operation['route_name'],
181
                    '_api_subresource_context' => [
182
                        'property' => $operation['property'],
183
                        'identifiers' => $operation['identifiers'],
184
                        'collection' => $isCollection,
185
                    ],
186
                ],
187
                [],
188
                [],
189
                '',
190
                [],
191
                ['GET']
192
            );
193
194
            $routeCollection->add($operation['route_name'], $route);
195
196
            $this->computeSubresourceOperations($routeCollection, $subresource, $rootResourceClass, $operation);
197
        }
198
    }
199
200
    /**
201
     * {@inheritdoc}
202
     */
203
    public function supports($resource, $type = null)
204
    {
205
        return 'api_platform' === $type;
206
    }
207
208
    /**
209
     * Load external files.
210
     *
211
     * @param RouteCollection $routeCollection
212
     */
213
    private function loadExternalFiles(RouteCollection $routeCollection)
214
    {
215
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
216
217
        if (isset($this->formats['jsonld'])) {
218
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
219
        }
220
    }
221
222
    /**
223
     * Creates and adds a route for the given operation to the route collection.
224
     *
225
     * @param RouteCollection $routeCollection
226
     * @param string          $resourceClass
227
     * @param string          $operationName
228
     * @param array           $operation
229
     * @param string          $resourceShortName
230
     * @param string          $operationType
231
     *
232
     * @throws RuntimeException
233
     */
234
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, string $operationType)
235
    {
236
        if (isset($operation['route_name'])) {
237
            return;
238
        }
239
240
        if (!isset($operation['method'])) {
241
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
242
        }
243
244
        $controller = $operation['controller'] ?? null;
245
        $actionName = sprintf('%s_%s', strtolower($operation['method']), $operationType);
246
247
        if (null === $controller) {
248
            $controller = self::DEFAULT_ACTION_PATTERN.$actionName;
249
250
            if (!$this->container->has($controller)) {
251
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
252
            }
253
        }
254
255
        if ($operationName !== strtolower($operation['method'])) {
256
            $actionName = sprintf('%s_%s', $operationName, $operationType);
257
        }
258
259
        $path = $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType);
260
261
        $resourceRouteName = $this->routeNameResolver($resourceShortName);
262
        $routeName = sprintf('%s%s_%s', self::ROUTE_NAME_PREFIX, $resourceRouteName, $actionName);
263
264
        $route = new Route(
265
            $path,
266
            [
267
                '_controller' => $controller,
268
                '_format' => null,
269
                '_api_resource_class' => $resourceClass,
270
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
271
            ],
272
            [],
273
            [],
274
            '',
275
            [],
276
            [$operation['method']]
277
        );
278
279
        $routeCollection->add($routeName, $route);
280
    }
281
282
    /**
283
     * Checks if a given subresource class has already been declared in the parent operation.
284
     *
285
     * @param string subresource
286
     * @param array  parentOperation
287
     *
288
     * @return bool
289
     */
290
    private function isRecursiveSubresource(string $subresource, array $parentOperation): bool
291
    {
292
        foreach ($parentOperation['identifiers'] as list($id, $resourceClass)) {
293
            if ($resourceClass === $subresource) {
294
                return true;
295
            }
296
        }
297
298
        return false;
299
    }
300
}
301