Completed
Pull Request — master (#1245)
by Antoine
04:59 queued 01:25
created

ApiLoader   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 162
Duplicated Lines 6.17 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 15
dl 10
loc 162
rs 9.1666
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
C load() 10 58 10
A supports() 0 4 1
A loadExternalFiles() 0 8 2
B addRoute() 0 35 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\PathResolver\OperationPathResolverInterface;
22
use Symfony\Component\Config\FileLocator;
23
use Symfony\Component\Config\Loader\Loader;
24
use Symfony\Component\Config\Resource\DirectoryResource;
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
    /**
39
     * @deprecated since version 2.1, to be removed in 3.0. Use {@see RouteNameGenerator::ROUTE_NAME_PREFIX} instead.
40
     */
41
    const ROUTE_NAME_PREFIX = 'api_';
42
    const DEFAULT_ACTION_PATTERN = 'api_platform.action.';
43
44
    private $fileLoader;
45
    private $propertyNameCollectionFactory;
46
    private $propertyMetadataFactory;
47
    private $resourceNameCollectionFactory;
48
    private $resourceMetadataFactory;
49
    private $operationPathResolver;
50
    private $container;
51
    private $formats;
52
    private $resourceClassDirectories;
53
54
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, OperationPathResolverInterface $operationPathResolver, ContainerInterface $container, array $formats, array $resourceClassDirectories = [], SubresourceOperationFactory $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;
0 ignored issues
show
Bug introduced by
The property subresourceOperationFactory does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
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 $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
                        ],
115
                    ],
116
                    [],
117
                    [],
118
                    '',
119
                    [],
120
                    ['GET']
121
                ));
122
            }
123
        }
124
125
        return $routeCollection;
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     */
131
    public function supports($resource, $type = null)
132
    {
133
        return 'api_platform' === $type;
134
    }
135
136
    /**
137
     * Load external files.
138
     *
139
     * @param RouteCollection $routeCollection
140
     */
141
    private function loadExternalFiles(RouteCollection $routeCollection)
142
    {
143
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
144
145
        if (isset($this->formats['jsonld'])) {
146
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
147
        }
148
    }
149
150
    /**
151
     * Creates and adds a route for the given operation to the route collection.
152
     *
153
     * @param RouteCollection $routeCollection
154
     * @param string          $resourceClass
155
     * @param string          $operationName
156
     * @param array           $operation
157
     * @param string          $resourceShortName
158
     * @param string          $operationType
159
     *
160
     * @throws RuntimeException
161
     */
162
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, string $operationType)
163
    {
164
        if (isset($operation['route_name'])) {
165
            return;
166
        }
167
168
        if (!isset($operation['method'])) {
169
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
170
        }
171
172
        if (null === $controller = $operation['controller'] ?? null) {
173
            $controller = sprintf('%s%s_%s', self::DEFAULT_ACTION_PATTERN, strtolower($operation['method']), $operationType);
174
175
            if (!$this->container->has($controller)) {
176
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $operationType, $operation['method']));
177
            }
178
        }
179
180
        $route = new Route(
181
            $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...
182
            [
183
                '_controller' => $controller,
184
                '_format' => null,
185
                '_api_resource_class' => $resourceClass,
186
                sprintf('_api_%s_operation_name', $operationType) => $operationName,
187
            ],
188
            [],
189
            [],
190
            '',
191
            [],
192
            [$operation['method']]
193
        );
194
195
        $routeCollection->add(RouteNameGenerator::generate($operationName, $resourceShortName, $operationType), $route);
196
    }
197
}
198