Completed
Pull Request — master (#904)
by Antoine
03:10
created

ApiLoader::load()   D

Complexity

Conditions 9
Paths 16

Size

Total Lines 40
Code Lines 21

Duplication

Lines 10
Ratio 25 %

Importance

Changes 0
Metric Value
dl 10
loc 40
rs 4.909
c 0
b 0
f 0
cc 9
eloc 21
nc 16
nop 2
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
namespace ApiPlatform\Core\Bridge\Symfony\Routing;
13
14
use ApiPlatform\Core\Exception\InvalidResourceException;
15
use ApiPlatform\Core\Exception\RuntimeException;
16
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
17
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
18
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
19
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
20
use ApiPlatform\Core\PathResolver\OperationPathResolverInterface;
21
use ApiPlatform\Core\Util\OperationTypes;
22
use Doctrine\Common\Inflector\Inflector;
23
use Symfony\Component\Config\FileLocator;
24
use Symfony\Component\Config\Loader\Loader;
25
use Symfony\Component\DependencyInjection\ContainerInterface;
26
use Symfony\Component\HttpKernel\KernelInterface;
27
use Symfony\Component\Routing\Loader\XmlFileLoader;
28
use Symfony\Component\Routing\Route;
29
use Symfony\Component\Routing\RouteCollection;
30
31
/**
32
 * Loads Resources.
33
 *
34
 * @author Kévin Dunglas <[email protected]>
35
 */
36
final class ApiLoader extends Loader
37
{
38
    const ROUTE_NAME_PREFIX = 'api_';
39
    const DEFAULT_ACTION_PATTERN = 'api_platform.action.';
40
41
    private $fileLoader;
42
    private $propertyNameCollectionFactory;
43
    private $propertyMetadataFactory;
44
    private $resourceNameCollectionFactory;
45
    private $resourceMetadataFactory;
46
    private $operationPathResolver;
47
    private $container;
48
    private $formats;
49
50
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, OperationPathResolverInterface $operationPathResolver, ContainerInterface $container, array $formats)
51
    {
52
        $this->fileLoader = new XmlFileLoader(new FileLocator($kernel->locateResource('@ApiPlatformBundle/Resources/config/routing')));
53
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
54
        $this->resourceMetadataFactory = $resourceMetadataFactory;
55
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
56
        $this->propertyMetadataFactory = $propertyMetadataFactory;
57
        $this->operationPathResolver = $operationPathResolver;
58
        $this->container = $container;
59
        $this->formats = $formats;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function load($data, $type = null)
66
    {
67
        $routeCollection = new RouteCollection();
68
69
        $this->loadExternalFiles($routeCollection);
70
71
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
72
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
73
            $resourceShortName = $resourceMetadata->getShortName();
74
75
            if (null === $resourceShortName) {
76
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
77
            }
78
79 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...
80
                foreach ($collectionOperations as $operationName => $operation) {
81
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationTypes::COLLECTION);
82
                }
83
            }
84
85 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...
86
                foreach ($itemOperations as $operationName => $operation) {
87
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, OperationTypes::ITEM);
88
                }
89
            }
90
91
            foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $property) {
92
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $property);
93
94
                if (null === $subcollection = $propertyMetadata->getSubcollection()) {
95
                    continue;
96
                }
97
98
                $operation = ['method' => 'GET', 'property' => $property, 'subcollection' => $subcollection];
99
                $this->addRoute($routeCollection, $resourceClass, 'get_'.strtolower($property), $operation, $resourceShortName, OperationTypes::SUBCOLLECTION);
100
            }
101
        }
102
103
        return $routeCollection;
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109
    public function supports($resource, $type = null)
110
    {
111
        return 'api_platform' === $type;
112
    }
113
114
    /**
115
     * Load external files.
116
     *
117
     * @param RouteCollection $routeCollection
118
     */
119
    private function loadExternalFiles(RouteCollection $routeCollection)
120
    {
121
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
122
123
        if (isset($this->formats['jsonld'])) {
124
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
125
        }
126
    }
127
128
    /**
129
     * Creates and adds a route for the given operation to the route collection.
130
     *
131
     * @param RouteCollection $routeCollection
132
     * @param string          $resourceClass
133
     * @param string          $operationName
134
     * @param array           $operation
135
     * @param string          $resourceShortName
136
     * @param bool            $collection
0 ignored issues
show
Documentation introduced by
There is no parameter named $collection. Did you maybe mean $routeCollection?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
137
     *
138
     * @throws RuntimeException
139
     */
140
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, string $operationType)
141
    {
142
        if (isset($operation['route_name'])) {
143
            return;
144
        }
145
146
        if (!isset($operation['method'])) {
147
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
148
        }
149
150
        $controller = $operation['controller'] ?? null;
151
        $actionName = sprintf('%s_%s', strtolower($operation['method']), $operationType);
152
153
        if (null === $controller) {
154
            $controller = self::DEFAULT_ACTION_PATTERN.$actionName;
155
156
            if (!$this->container->has($controller)) {
157
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
158
            }
159
        }
160
161
        if ($operationName !== strtolower($operation['method'])) {
162
            $actionName = sprintf('%s_%s', $operationName, $operationType);
163
        }
164
165
        $path = $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType);
166
167
        $resourceRouteName = Inflector::pluralize(Inflector::tableize($resourceShortName));
168
        $routeName = sprintf('%s%s_%s', self::ROUTE_NAME_PREFIX, $resourceRouteName, $actionName);
169
170
        $route = new Route(
171
            $path,
172
            [
173
                '_controller' => $controller,
174
                '_format' => null,
175
                '_api_resource_class' => $resourceClass,
176
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
177
                '_api_subcollection_property_name' => $operation['property'] ?? null,
178
                '_api_subcollection_resource_class' => $operation['subcollection'] ?? null,
179
            ],
180
            [],
181
            [],
182
            '',
183
            [],
184
            [$operation['method']]
185
        );
186
187
        $routeCollection->add($routeName, $route);
188
    }
189
}
190