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

ApiLoader::addRoute()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 47
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

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