Passed
Pull Request — master (#2598)
by Torrey
05:18
created

ApiLoader   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 194
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 104
dl 0
loc 194
rs 10
c 0
b 0
f 0
wmc 24

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 1
B load() 0 63 10
A addRoute() 0 32 2
A resolveOperationController() 0 11 3
A assertOperationMethod() 0 4 2
A loadExternalFiles() 0 18 5
A supports() 0 3 1
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
                $this->assertOperationMethod($resourceClass, $operationId, $operation);
113
114
                $controller = $this->resolveOperationController($operation, OperationType::SUBRESOURCE);
115
116
                $routeCollection->add($operation['route_name'], new Route(
117
                    $operation['path'],
118
                    [
119
                        '_controller' => $controller,
120
                        '_format' => null,
121
                        '_api_resource_class' => $operation['resource_class'],
122
                        '_api_subresource_operation_name' => $operation['route_name'],
123
                        '_api_subresource_context' => [
124
                            'property' => $operation['property'],
125
                            'identifiers' => $operation['identifiers'],
126
                            'collection' => $operation['collection'],
127
                            'operationId' => $operationId,
128
                        ],
129
                    ] + ($operation['defaults'] ?? []),
130
                    $operation['requirements'] ?? [],
131
                    $operation['options'] ?? [],
132
                    $operation['host'] ?? '',
133
                    $operation['schemes'] ?? [],
134
                    [$operation['method']],
135
                    $operation['condition'] ?? ''
136
                ));
137
            }
138
        }
139
140
        return $routeCollection;
141
    }
142
143
    /**
144
     * {@inheritdoc}
145
     */
146
    public function supports($resource, $type = null)
147
    {
148
        return 'api_platform' === $type;
149
    }
150
151
    /**
152
     * Load external files.
153
     */
154
    private function loadExternalFiles(RouteCollection $routeCollection): void
155
    {
156
        if ($this->entrypointEnabled) {
157
            $routeCollection->addCollection($this->fileLoader->load('api.xml'));
158
        }
159
160
        if ($this->docsEnabled) {
161
            $routeCollection->addCollection($this->fileLoader->load('docs.xml'));
162
        }
163
164
        if ($this->graphqlEnabled) {
165
            $graphqlCollection = $this->fileLoader->load('graphql.xml');
166
            $graphqlCollection->addDefaults(['_graphql' => true]);
167
            $routeCollection->addCollection($graphqlCollection);
168
        }
169
170
        if (isset($this->formats['jsonld'])) {
171
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
172
        }
173
    }
174
175
    /**
176
     * Creates and adds a route for the given operation to the route collection.
177
     *
178
     * @throws RuntimeException
179
     */
180
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, ResourceMetadata $resourceMetadata, string $operationType): void
181
    {
182
        $resourceShortName = $resourceMetadata->getShortName();
183
184
        if (isset($operation['route_name'])) {
185
            return;
186
        }
187
188
        $this->assertOperationMethod($resourceClass, $operationName, $operation);
189
190
        $controller = $this->resolveOperationController($operation, $operationType);
191
192
        $path = trim(trim($resourceMetadata->getAttribute('route_prefix', '')), '/');
193
        $path .= $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType, $operationName);
0 ignored issues
show
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

193
        $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...
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

193
        $path .= $this->operationPathResolver->resolveOperationPath(/** @scrutinizer ignore-type */ $resourceShortName, $operation, $operationType, $operationName);
Loading history...
194
195
        $route = new Route(
196
            $path,
197
            [
198
                '_controller' => $controller,
199
                '_format' => null,
200
                '_api_resource_class' => $resourceClass,
201
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
202
            ] + ($operation['defaults'] ?? []),
203
            $operation['requirements'] ?? [],
204
            $operation['options'] ?? [],
205
            $operation['host'] ?? '',
206
            $operation['schemes'] ?? [],
207
            [$operation['method']],
208
            $operation['condition'] ?? ''
209
        );
210
211
        $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

211
        $routeCollection->add(RouteNameGenerator::generate($operationName, /** @scrutinizer ignore-type */ $resourceShortName, $operationType), $route);
Loading history...
212
    }
213
214
    private function assertOperationMethod(string $resourceClass, string $operationName, array $operation)
215
    {
216
        if (!isset($operation['method'])) {
217
            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));
218
        }
219
    }
220
221
    private function resolveOperationController(array $operation, string $operationType): string
222
    {
223
        if (null === $controller = $operation['controller'] ?? null) {
224
            $controller = sprintf('%s%s_%s', self::DEFAULT_ACTION_PATTERN, strtolower($operation['method']), $operationType);
225
226
            if (!$this->container->has($controller)) {
227
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
228
            }
229
        }
230
231
        return $controller;
232
    }
233
}
234