Passed
Push — master ( 8b9203...a62a07 )
by Kévin
03:38
created

ApiLoader::addRoute()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 44
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 27
c 0
b 0
f 0
nc 6
nop 6
dl 0
loc 44
rs 8.5546
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\Resource\Factory\ResourceMetadataFactoryInterface;
20
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
21
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
22
use ApiPlatform\Core\Operation\Factory\SubresourceOperationFactoryInterface;
23
use ApiPlatform\Core\PathResolver\OperationPathResolverInterface;
24
use Symfony\Component\Config\FileLocator;
25
use Symfony\Component\Config\Loader\Loader;
26
use Symfony\Component\Config\Resource\DirectoryResource;
27
use Symfony\Component\DependencyInjection\ContainerInterface;
28
use Symfony\Component\HttpKernel\KernelInterface;
29
use Symfony\Component\Routing\Loader\XmlFileLoader;
30
use Symfony\Component\Routing\Route;
31
use Symfony\Component\Routing\RouteCollection;
32
33
/**
34
 * Loads Resources.
35
 *
36
 * @author Kévin Dunglas <[email protected]>
37
 */
38
final class ApiLoader extends Loader
39
{
40
    /**
41
     * @deprecated since version 2.1, to be removed in 3.0. Use {@see RouteNameGenerator::ROUTE_NAME_PREFIX} instead.
42
     */
43
    public const ROUTE_NAME_PREFIX = 'api_';
44
    public const DEFAULT_ACTION_PATTERN = 'api_platform.action.';
45
46
    private $fileLoader;
47
    private $resourceNameCollectionFactory;
48
    private $resourceMetadataFactory;
49
    private $operationPathResolver;
50
    private $container;
51
    private $formats;
52
    private $resourceClassDirectories;
53
    private $subresourceOperationFactory;
54
    private $graphqlEnabled;
55
    private $entrypointEnabled;
56
    private $docsEnabled;
57
58
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, OperationPathResolverInterface $operationPathResolver, ContainerInterface $container, array $formats, array $resourceClassDirectories = [], SubresourceOperationFactoryInterface $subresourceOperationFactory = null, bool $graphqlEnabled = false, bool $entrypointEnabled = true, bool $docsEnabled = true)
59
    {
60
        /** @var string[]|string $paths */
61
        $paths = $kernel->locateResource('@ApiPlatformBundle/Resources/config/routing');
62
        $this->fileLoader = new XmlFileLoader(new FileLocator($paths));
63
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
64
        $this->resourceMetadataFactory = $resourceMetadataFactory;
65
        $this->operationPathResolver = $operationPathResolver;
66
        $this->container = $container;
67
        $this->formats = $formats;
68
        $this->resourceClassDirectories = $resourceClassDirectories;
69
        $this->subresourceOperationFactory = $subresourceOperationFactory;
70
        $this->graphqlEnabled = $graphqlEnabled;
71
        $this->entrypointEnabled = $entrypointEnabled;
72
        $this->docsEnabled = $docsEnabled;
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    public function load($data, $type = null): RouteCollection
79
    {
80
        $routeCollection = new RouteCollection();
81
        foreach ($this->resourceClassDirectories as $directory) {
82
            $routeCollection->addResource(new DirectoryResource($directory, '/\.php$/'));
83
        }
84
85
        $this->loadExternalFiles($routeCollection);
86
87
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
88
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
89
            $resourceShortName = $resourceMetadata->getShortName();
90
91
            if (null === $resourceShortName) {
92
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
93
            }
94
95
            if (null !== $collectionOperations = $resourceMetadata->getCollectionOperations()) {
96
                foreach ($collectionOperations as $operationName => $operation) {
97
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceMetadata, OperationType::COLLECTION);
98
                }
99
            }
100
101
            if (null !== $itemOperations = $resourceMetadata->getItemOperations()) {
102
                foreach ($itemOperations as $operationName => $operation) {
103
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceMetadata, OperationType::ITEM);
104
                }
105
            }
106
107
            if (null === $this->subresourceOperationFactory) {
108
                continue;
109
            }
110
111
            foreach ($this->subresourceOperationFactory->create($resourceClass) as $operationId => $operation) {
112
                if (null === $controller = $operation['controller'] ?? null) {
113
                    $controller = self::DEFAULT_ACTION_PATTERN.'get_subresource';
114
115
                    if (!$this->container->has($controller)) {
116
                        throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', OperationType::SUBRESOURCE, 'GET'));
117
                    }
118
                }
119
120
                $routeCollection->add($operation['route_name'], new Route(
121
                    $operation['path'],
122
                    [
123
                        '_controller' => $controller,
124
                        '_format' => null,
125
                        '_api_resource_class' => $operation['resource_class'],
126
                        '_api_subresource_operation_name' => $operation['route_name'],
127
                        '_api_subresource_context' => [
128
                            'property' => $operation['property'],
129
                            'identifiers' => $operation['identifiers'],
130
                            'collection' => $operation['collection'],
131
                            'operationId' => $operationId,
132
                        ],
133
                    ] + ($operation['defaults'] ?? []),
134
                    $operation['requirements'] ?? [],
135
                    $operation['options'] ?? [],
136
                    $operation['host'] ?? '',
137
                    $operation['schemes'] ?? [],
138
                    ['GET'],
139
                    $operation['condition'] ?? ''
140
                ));
141
            }
142
        }
143
144
        return $routeCollection;
145
    }
146
147
    /**
148
     * {@inheritdoc}
149
     */
150
    public function supports($resource, $type = null)
151
    {
152
        return 'api_platform' === $type;
153
    }
154
155
    /**
156
     * Load external files.
157
     */
158
    private function loadExternalFiles(RouteCollection $routeCollection): void
159
    {
160
        if ($this->entrypointEnabled) {
161
            $routeCollection->addCollection($this->fileLoader->load('api.xml'));
162
        }
163
164
        if ($this->docsEnabled) {
165
            $routeCollection->addCollection($this->fileLoader->load('docs.xml'));
166
        }
167
168
        if ($this->graphqlEnabled) {
169
            $graphqlCollection = $this->fileLoader->load('graphql.xml');
170
            $graphqlCollection->addDefaults(['_graphql' => true]);
171
            $routeCollection->addCollection($graphqlCollection);
172
        }
173
174
        if (isset($this->formats['jsonld'])) {
175
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
176
        }
177
    }
178
179
    /**
180
     * Creates and adds a route for the given operation to the route collection.
181
     *
182
     * @throws RuntimeException
183
     */
184
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, ResourceMetadata $resourceMetadata, string $operationType): void
185
    {
186
        $resourceShortName = $resourceMetadata->getShortName();
187
188
        if (isset($operation['route_name'])) {
189
            if (!isset($operation['method'])) {
190
                @trigger_error(sprintf('Not setting the "method" attribute is deprecated and will not be supported anymore in API Platform 3.0, set it for the %s operation "%s" of the class "%s".', OperationType::COLLECTION === $operationType ? 'collection' : 'item', $operationName, $resourceClass), E_USER_DEPRECATED);
191
            }
192
193
            return;
194
        }
195
196
        if (!isset($operation['method'])) {
197
            throw new RuntimeException(sprintf('Either a "route_name" or a "method" operation attribute must exist for the operation "%s" of the resource "%s".', $operationName, $resourceClass));
198
        }
199
200
        if (null === $controller = $operation['controller'] ?? null) {
201
            $controller = sprintf('%s%s_%s', self::DEFAULT_ACTION_PATTERN, strtolower($operation['method']), $operationType);
202
203
            if (!$this->container->has($controller)) {
204
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
205
            }
206
        }
207
208
        $path = trim(trim($resourceMetadata->getAttribute('route_prefix', '')), '/');
209
        $path .= $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType, $operationName);
0 ignored issues
show
Bug introduced by
It seems like $resourceShortName can also be of type null; however, parameter $resourceShortName of ApiPlatform\Core\PathRes...:resolveOperationPath() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

209
        $path .= $this->operationPathResolver->resolveOperationPath(/** @scrutinizer ignore-type */ $resourceShortName, $operation, $operationType, $operationName);
Loading history...
Unused Code introduced by
The call to ApiPlatform\Core\PathRes...:resolveOperationPath() has too many arguments starting with $operationName. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

209
        $path .= $this->operationPathResolver->/** @scrutinizer ignore-call */ resolveOperationPath($resourceShortName, $operation, $operationType, $operationName);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
210
211
        $route = new Route(
212
            $path,
213
            [
214
                '_controller' => $controller,
215
                '_format' => null,
216
                '_api_resource_class' => $resourceClass,
217
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
218
            ] + ($operation['defaults'] ?? []),
219
            $operation['requirements'] ?? [],
220
            $operation['options'] ?? [],
221
            $operation['host'] ?? '',
222
            $operation['schemes'] ?? [],
223
            [$operation['method']],
224
            $operation['condition'] ?? ''
225
        );
226
227
        $routeCollection->add(RouteNameGenerator::generate($operationName, $resourceShortName, $operationType), $route);
0 ignored issues
show
Bug introduced by
It seems like $resourceShortName can also be of type null; however, parameter $resourceShortName of ApiPlatform\Core\Bridge\...meGenerator::generate() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

227
        $routeCollection->add(RouteNameGenerator::generate($operationName, /** @scrutinizer ignore-type */ $resourceShortName, $operationType), $route);
Loading history...
228
    }
229
}
230