Completed
Pull Request — master (#1245)
by Antoine
03:09
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 $propertyNameCollectionFactory;
47
    private $propertyMetadataFactory;
48
    private $resourceNameCollectionFactory;
49
    private $resourceMetadataFactory;
50
    private $operationPathResolver;
51
    private $container;
52
    private $formats;
53
    private $resourceClassDirectories;
54
    private $subresourceOperationFactory;
55
56
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, OperationPathResolverInterface $operationPathResolver, ContainerInterface $container, array $formats, array $resourceClassDirectories = [], SubresourceOperationFactoryInterface $subresourceOperationFactory = null)
57
    {
58
        $this->fileLoader = new XmlFileLoader(new FileLocator($kernel->locateResource('@ApiPlatformBundle/Resources/config/routing')));
59
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
60
        $this->resourceMetadataFactory = $resourceMetadataFactory;
61
        $this->operationPathResolver = $operationPathResolver;
62
        $this->container = $container;
63
        $this->formats = $formats;
64
        $this->resourceClassDirectories = $resourceClassDirectories;
65
        $this->subresourceOperationFactory = $subresourceOperationFactory;
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function load($data, $type = null): RouteCollection
72
    {
73
        $routeCollection = new RouteCollection();
74
        foreach ($this->resourceClassDirectories as $directory) {
75
            $routeCollection->addResource(new DirectoryResource($directory, '/\.php$/'));
76
        }
77
78
        $this->loadExternalFiles($routeCollection);
79
80
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
81
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
82
            $resourceShortName = $resourceMetadata->getShortName();
83
84
            if (null === $resourceShortName) {
85
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
86
            }
87
88 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...
89
                foreach ($collectionOperations as $operationName => $operation) {
90
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationType::COLLECTION);
91
                }
92
            }
93
94 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...
95
                foreach ($itemOperations as $operationName => $operation) {
96
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationType::ITEM);
97
                }
98
            }
99
100
            if (null === $this->subresourceOperationFactory) {
101
                continue;
102
            }
103
104
            foreach ($this->subresourceOperationFactory->create($resourceClass) as $operation) {
105
                $routeCollection->add($operation['route_name'], new Route(
106
                    $operation['path'],
107
                    [
108
                        '_controller' => self::DEFAULT_ACTION_PATTERN.'get_subresource',
109
                        '_format' => null,
110
                        '_api_resource_class' => $operation['resource_class'],
111
                        '_api_subresource_operation_name' => $operation['route_name'],
112
                        '_api_subresource_context' => [
113
                            'property' => $operation['property'],
114
                            'identifiers' => $operation['identifiers'],
115
                            'collection' => $operation['collection'],
116
                        ],
117
                    ],
118
                    [],
119
                    [],
120
                    '',
121
                    [],
122
                    ['GET']
123
                ));
124
            }
125
        }
126
127
        return $routeCollection;
128
    }
129
130
    /**
131
     * {@inheritdoc}
132
     */
133
    public function supports($resource, $type = null)
134
    {
135
        return 'api_platform' === $type;
136
    }
137
138
    /**
139
     * Load external files.
140
     *
141
     * @param RouteCollection $routeCollection
142
     */
143
    private function loadExternalFiles(RouteCollection $routeCollection)
144
    {
145
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
146
147
        if (isset($this->formats['jsonld'])) {
148
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
149
        }
150
    }
151
152
    /**
153
     * Creates and adds a route for the given operation to the route collection.
154
     *
155
     * @param RouteCollection $routeCollection
156
     * @param string          $resourceClass
157
     * @param string          $operationName
158
     * @param array           $operation
159
     * @param string          $resourceShortName
160
     * @param string          $operationType
161
     *
162
     * @throws RuntimeException
163
     */
164
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, string $operationType)
165
    {
166
        if (isset($operation['route_name'])) {
167
            return;
168
        }
169
170
        if (!isset($operation['method'])) {
171
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
172
        }
173
174
        if (null === $controller = $operation['controller'] ?? null) {
175
            $controller = sprintf('%s%s_%s', self::DEFAULT_ACTION_PATTERN, strtolower($operation['method']), $operationType);
176
177
            if (!$this->container->has($controller)) {
178
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
179
            }
180
        }
181
182
        $route = new Route(
183
            $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...
184
            [
185
                '_controller' => $controller,
186
                '_format' => null,
187
                '_api_resource_class' => $resourceClass,
188
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
189
            ],
190
            [],
191
            [],
192
            '',
193
            [],
194
            [$operation['method']]
195
        );
196
197
        $routeCollection->add(RouteNameGenerator::generate($operationName, $resourceShortName, $operationType), $route);
198
    }
199
}
200