Completed
Push — master ( 131c91...75b368 )
by Kévin
03:30
created

ApiLoader::loadExternalFiles()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 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\Operation\Factory\SubresourceOperationFactoryInterface;
22
use ApiPlatform\Core\PathResolver\OperationPathResolverInterface;
23
use Symfony\Component\Config\FileLocator;
24
use Symfony\Component\Config\Loader\Loader;
25
use Symfony\Component\Config\Resource\DirectoryResource;
26
use Symfony\Component\DependencyInjection\ContainerInterface;
27
use Symfony\Component\HttpKernel\KernelInterface;
28
use Symfony\Component\Routing\Loader\XmlFileLoader;
29
use Symfony\Component\Routing\Route;
30
use Symfony\Component\Routing\RouteCollection;
31
32
/**
33
 * Loads Resources.
34
 *
35
 * @author Kévin Dunglas <[email protected]>
36
 */
37
final class ApiLoader extends Loader
38
{
39
    /**
40
     * @deprecated since version 2.1, to be removed in 3.0. Use {@see RouteNameGenerator::ROUTE_NAME_PREFIX} instead.
41
     */
42
    const ROUTE_NAME_PREFIX = 'api_';
43
    const DEFAULT_ACTION_PATTERN = 'api_platform.action.';
44
45
    private $fileLoader;
46
    private $resourceNameCollectionFactory;
47
    private $resourceMetadataFactory;
48
    private $operationPathResolver;
49
    private $container;
50
    private $formats;
51
    private $resourceClassDirectories;
52
    private $subresourceOperationFactory;
53
54
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, OperationPathResolverInterface $operationPathResolver, ContainerInterface $container, array $formats, array $resourceClassDirectories = [], SubresourceOperationFactoryInterface $subresourceOperationFactory = null)
55
    {
56
        $this->fileLoader = new XmlFileLoader(new FileLocator($kernel->locateResource('@ApiPlatformBundle/Resources/config/routing')));
57
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
58
        $this->resourceMetadataFactory = $resourceMetadataFactory;
59
        $this->operationPathResolver = $operationPathResolver;
60
        $this->container = $container;
61
        $this->formats = $formats;
62
        $this->resourceClassDirectories = $resourceClassDirectories;
63
        $this->subresourceOperationFactory = $subresourceOperationFactory;
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function load($data, $type = null): RouteCollection
70
    {
71
        $routeCollection = new RouteCollection();
72
        foreach ($this->resourceClassDirectories as $directory) {
73
            $routeCollection->addResource(new DirectoryResource($directory, '/\.php$/'));
74
        }
75
76
        $this->loadExternalFiles($routeCollection);
77
78
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
79
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
80
            $resourceShortName = $resourceMetadata->getShortName();
81
82
            if (null === $resourceShortName) {
83
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
84
            }
85
86 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...
87
                foreach ($collectionOperations as $operationName => $operation) {
88
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationType::COLLECTION);
89
                }
90
            }
91
92 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...
93
                foreach ($itemOperations as $operationName => $operation) {
94
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationType::ITEM);
95
                }
96
            }
97
98
            if (null === $this->subresourceOperationFactory) {
99
                continue;
100
            }
101
102
            foreach ($this->subresourceOperationFactory->create($resourceClass) as $operationId => $operation) {
103
                $routeCollection->add($operation['route_name'], new Route(
104
                    $operation['path'],
105
                    [
106
                        '_controller' => self::DEFAULT_ACTION_PATTERN.'get_subresource',
107
                        '_format' => null,
108
                        '_api_resource_class' => $operation['resource_class'],
109
                        '_api_subresource_operation_name' => $operation['route_name'],
110
                        '_api_subresource_context' => [
111
                            'property' => $operation['property'],
112
                            'identifiers' => $operation['identifiers'],
113
                            'collection' => $operation['collection'],
114
                            'operationId' => $operationId,
115
                        ],
116
                    ],
117
                    [],
118
                    [],
119
                    '',
120
                    [],
121
                    ['GET']
122
                ));
123
            }
124
        }
125
126
        return $routeCollection;
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public function supports($resource, $type = null)
133
    {
134
        return 'api_platform' === $type;
135
    }
136
137
    /**
138
     * Load external files.
139
     *
140
     * @param RouteCollection $routeCollection
141
     */
142
    private function loadExternalFiles(RouteCollection $routeCollection)
143
    {
144
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
145
146
        if (isset($this->formats['jsonld'])) {
147
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
148
        }
149
    }
150
151
    /**
152
     * Creates and adds a route for the given operation to the route collection.
153
     *
154
     * @param RouteCollection $routeCollection
155
     * @param string          $resourceClass
156
     * @param string          $operationName
157
     * @param array           $operation
158
     * @param string          $resourceShortName
159
     * @param string          $operationType
160
     *
161
     * @throws RuntimeException
162
     */
163
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, string $operationType)
164
    {
165
        if (isset($operation['route_name'])) {
166
            return;
167
        }
168
169
        if (!isset($operation['method'])) {
170
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
171
        }
172
173
        if (null === $controller = $operation['controller'] ?? null) {
174
            $controller = sprintf('%s%s_%s', self::DEFAULT_ACTION_PATTERN, strtolower($operation['method']), $operationType);
175
176
            if (!$this->container->has($controller)) {
177
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
178
            }
179
        }
180
181
        $route = new Route(
182
            $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType, $operationName),
0 ignored issues
show
Unused Code introduced by
The call to OperationPathResolverInt...:resolveOperationPath() has too many arguments starting with $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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
183
            [
184
                '_controller' => $controller,
185
                '_format' => null,
186
                '_api_resource_class' => $resourceClass,
187
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
188
            ],
189
            [],
190
            [],
191
            '',
192
            [],
193
            [$operation['method']]
194
        );
195
196
        $routeCollection->add(RouteNameGenerator::generate($operationName, $resourceShortName, $operationType), $route);
197
    }
198
}
199