Passed
Push — master ( 8bd912...d93388 )
by Alan
06:58 queued 02:20
created

src/Bridge/Symfony/Routing/ApiLoader.php (2 issues)

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 $graphiQlEnabled;
56
    private $graphQlPlaygroundEnabled;
57
    private $entrypointEnabled;
58
    private $docsEnabled;
59
60
    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, bool $graphiQlEnabled = false, bool $graphQlPlaygroundEnabled = false)
61
    {
62
        /** @var string[]|string $paths */
63
        $paths = $kernel->locateResource('@ApiPlatformBundle/Resources/config/routing');
64
        $this->fileLoader = new XmlFileLoader(new FileLocator($paths));
65
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
66
        $this->resourceMetadataFactory = $resourceMetadataFactory;
67
        $this->operationPathResolver = $operationPathResolver;
68
        $this->container = $container;
69
        $this->formats = $formats;
70
        $this->resourceClassDirectories = $resourceClassDirectories;
71
        $this->subresourceOperationFactory = $subresourceOperationFactory;
72
        $this->graphqlEnabled = $graphqlEnabled;
73
        $this->graphiQlEnabled = $graphiQlEnabled;
74
        $this->graphQlPlaygroundEnabled = $graphQlPlaygroundEnabled;
75
        $this->entrypointEnabled = $entrypointEnabled;
76
        $this->docsEnabled = $docsEnabled;
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function load($data, $type = null): RouteCollection
83
    {
84
        $routeCollection = new RouteCollection();
85
        foreach ($this->resourceClassDirectories as $directory) {
86
            $routeCollection->addResource(new DirectoryResource($directory, '/\.php$/'));
87
        }
88
89
        $this->loadExternalFiles($routeCollection);
90
91
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
92
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
93
            $resourceShortName = $resourceMetadata->getShortName();
94
95
            if (null === $resourceShortName) {
96
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
97
            }
98
99
            if (null !== $collectionOperations = $resourceMetadata->getCollectionOperations()) {
100
                foreach ($collectionOperations as $operationName => $operation) {
101
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceMetadata, OperationType::COLLECTION);
102
                }
103
            }
104
105
            if (null !== $itemOperations = $resourceMetadata->getItemOperations()) {
106
                foreach ($itemOperations as $operationName => $operation) {
107
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceMetadata, OperationType::ITEM);
108
                }
109
            }
110
111
            if (null === $this->subresourceOperationFactory) {
112
                continue;
113
            }
114
115
            foreach ($this->subresourceOperationFactory->create($resourceClass) as $operationId => $operation) {
116
                if (null === $controller = $operation['controller'] ?? null) {
117
                    $controller = self::DEFAULT_ACTION_PATTERN.'get_subresource';
118
119
                    if (!$this->container->has($controller)) {
120
                        throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', OperationType::SUBRESOURCE, 'GET'));
121
                    }
122
                }
123
124
                $routeCollection->add($operation['route_name'], new Route(
125
                    $operation['path'],
126
                    [
127
                        '_controller' => $controller,
128
                        '_format' => null,
129
                        '_api_resource_class' => $operation['resource_class'],
130
                        '_api_subresource_operation_name' => $operation['route_name'],
131
                        '_api_subresource_context' => [
132
                            'property' => $operation['property'],
133
                            'identifiers' => $operation['identifiers'],
134
                            'collection' => $operation['collection'],
135
                            'operationId' => $operationId,
136
                        ],
137
                    ] + ($operation['defaults'] ?? []),
138
                    $operation['requirements'] ?? [],
139
                    $operation['options'] ?? [],
140
                    $operation['host'] ?? '',
141
                    $operation['schemes'] ?? [],
142
                    ['GET'],
143
                    $operation['condition'] ?? ''
144
                ));
145
            }
146
        }
147
148
        return $routeCollection;
149
    }
150
151
    /**
152
     * {@inheritdoc}
153
     */
154
    public function supports($resource, $type = null)
155
    {
156
        return 'api_platform' === $type;
157
    }
158
159
    /**
160
     * Load external files.
161
     */
162
    private function loadExternalFiles(RouteCollection $routeCollection): void
163
    {
164
        if ($this->entrypointEnabled) {
165
            $routeCollection->addCollection($this->fileLoader->load('api.xml'));
166
        }
167
168
        if ($this->docsEnabled) {
169
            $routeCollection->addCollection($this->fileLoader->load('docs.xml'));
170
        }
171
172
        if ($this->graphqlEnabled) {
173
            $graphqlCollection = $this->fileLoader->load('graphql/graphql.xml');
174
            $graphqlCollection->addDefaults(['_graphql' => true]);
175
            $routeCollection->addCollection($graphqlCollection);
176
        }
177
178
        if ($this->graphiQlEnabled) {
179
            $graphiQlCollection = $this->fileLoader->load('graphql/graphiql.xml');
180
            $graphiQlCollection->addDefaults(['_graphql' => true]);
181
            $routeCollection->addCollection($graphiQlCollection);
182
        }
183
184
        if ($this->graphQlPlaygroundEnabled) {
185
            $graphQlPlaygroundCollection = $this->fileLoader->load('graphql/graphql_playground.xml');
186
            $graphQlPlaygroundCollection->addDefaults(['_graphql' => true]);
187
            $routeCollection->addCollection($graphQlPlaygroundCollection);
188
        }
189
190
        if (isset($this->formats['jsonld'])) {
191
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
192
        }
193
    }
194
195
    /**
196
     * Creates and adds a route for the given operation to the route collection.
197
     *
198
     * @throws RuntimeException
199
     */
200
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, ResourceMetadata $resourceMetadata, string $operationType): void
201
    {
202
        $resourceShortName = $resourceMetadata->getShortName();
203
204
        if (isset($operation['route_name'])) {
205
            if (!isset($operation['method'])) {
206
                @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);
207
            }
208
209
            return;
210
        }
211
212
        if (!isset($operation['method'])) {
213
            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));
214
        }
215
216
        if (null === $controller = $operation['controller'] ?? null) {
217
            $controller = sprintf('%s%s_%s', self::DEFAULT_ACTION_PATTERN, strtolower($operation['method']), $operationType);
218
219
            if (!$this->container->has($controller)) {
220
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
221
            }
222
        }
223
224
        $path = trim(trim($resourceMetadata->getAttribute('route_prefix', '')), '/');
225
        $path .= $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType, $operationName);
0 ignored issues
show
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

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

225
        $path .= $this->operationPathResolver->resolveOperationPath(/** @scrutinizer ignore-type */ $resourceShortName, $operation, $operationType, $operationName);
Loading history...
226
227
        $route = new Route(
228
            $path,
229
            [
230
                '_controller' => $controller,
231
                '_format' => null,
232
                '_api_resource_class' => $resourceClass,
233
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
234
            ] + ($operation['defaults'] ?? []),
235
            $operation['requirements'] ?? [],
236
            $operation['options'] ?? [],
237
            $operation['host'] ?? '',
238
            $operation['schemes'] ?? [],
239
            [$operation['method']],
240
            $operation['condition'] ?? ''
241
        );
242
243
        $routeCollection->add(RouteNameGenerator::generate($operationName, $resourceShortName, $operationType), $route);
244
    }
245
}
246