Completed
Pull Request — master (#625)
by Kévin
05:44 queued 02:31
created

ApiLoader::addRoute()   C

Complexity

Conditions 11
Paths 28

Size

Total Lines 58
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 58
rs 6.4179
cc 11
eloc 31
nc 28
nop 6

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Resource\Factory\ResourceMetadataFactoryInterface;
17
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
18
use ApiPlatform\Core\Naming\ResourcePathNamingStrategyInterface;
19
use Doctrine\Common\Inflector\Inflector;
20
use Symfony\Component\Config\FileLocator;
21
use Symfony\Component\Config\Loader\Loader;
22
use Symfony\Component\DependencyInjection\ContainerInterface;
23
use Symfony\Component\HttpKernel\KernelInterface;
24
use Symfony\Component\Routing\Loader\XmlFileLoader;
25
use Symfony\Component\Routing\Route;
26
use Symfony\Component\Routing\RouteCollection;
27
28
/**
29
 * Loads Resources.
30
 *
31
 * @author Kévin Dunglas <[email protected]>
32
 */
33
final class ApiLoader extends Loader
34
{
35
    const ROUTE_NAME_PREFIX = 'api_';
36
    const DEFAULT_ACTION_PATTERN = 'api_platform.action.';
37
38
    private $fileLoader;
39
    private $resourceNameCollectionFactory;
40
    private $resourceMetadataFactory;
41
    private $resourcePathGenerator;
42
    private $container;
43
    private $formats;
44
45
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, ResourcePathNamingStrategyInterface $resourcePathGenerator, ContainerInterface $container, array $formats)
46
    {
47
        $this->fileLoader = new XmlFileLoader(new FileLocator($kernel->locateResource('@ApiPlatformBundle/Resources/config/routing')));
48
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
49
        $this->resourceMetadataFactory = $resourceMetadataFactory;
50
        $this->resourcePathGenerator = $resourcePathGenerator;
51
        $this->container = $container;
52
        $this->formats = $formats;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function load($data, $type = null)
59
    {
60
        $routeCollection = new RouteCollection();
61
62
        $this->loadExternalFiles($routeCollection);
63
64
        if ($this->container->getParameter('api_platform.enable_swagger')) {
65
            $routeCollection->addCollection($this->fileLoader->load('swagger.xml'));
66
        }
67
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
68
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
69
            $resourceShortName = $resourceMetadata->getShortName();
70
71
            if (null === $resourceShortName) {
72
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
73
            }
74
75
            foreach ($resourceMetadata->getCollectionOperations() as $operationName => $operation) {
0 ignored issues
show
Bug introduced by
The expression $resourceMetadata->getCollectionOperations() of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
76
                $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, true);
77
            }
78
79
            foreach ($resourceMetadata->getItemOperations() as $operationName => $operation) {
0 ignored issues
show
Bug introduced by
The expression $resourceMetadata->getItemOperations() of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
80
                $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, false);
81
            }
82
        }
83
84
        return $routeCollection;
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function supports($resource, $type = null)
91
    {
92
        return 'api_platform' === $type;
93
    }
94
95
    /**
96
     * Load external files.
97
     *
98
     * @param RouteCollection $routeCollection
99
     */
100
    private function loadExternalFiles(RouteCollection $routeCollection)
101
    {
102
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
103
104
        if (isset($this->formats['jsonld'])) {
105
            $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
106
            $routeCollection->addCollection($this->fileLoader->load('hydra.xml'));
107
        }
108
    }
109
110
    /**
111
     * Creates and adds a route for the given operation to the route collection.
112
     *
113
     * @param RouteCollection $routeCollection
114
     * @param string          $resourceClass
115
     * @param string          $operationName
116
     * @param array           $operation
117
     * @param string          $resourceShortName
118
     * @param bool            $collection
119
     *
120
     * @throws RuntimeException
121
     */
122
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, bool $collection)
123
    {
124
        if (isset($operation['route_name'])) {
125
            return;
126
        }
127
128
        if (!isset($operation['method'])) {
129
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
130
        }
131
132
        $controller = $operation['controller'] ?? null;
133
        $collectionType = $collection ? 'collection' : 'item';
134
        $actionName = sprintf('%s_%s', strtolower($operation['method']), $collectionType);
135
136
        if (null === $controller) {
137
            $controller = self::DEFAULT_ACTION_PATTERN.$actionName;
138
139
            if (!$this->container->has($controller)) {
140
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $collectionType, $operation['method']));
141
            }
142
        }
143
144
        if ($operationName !== strtolower($operation['method'])) {
145
            $actionName = sprintf('%s_%s', $operationName, $collection ? 'collection' : 'item');
146
        }
147
148
        $path = $operation['path'] ?? null;
149
150
        if (null === $path) {
151
            $path = '/'.$this->resourcePathGenerator->generateResourceBasePath($resourceShortName);
152
153
            if (!$collection) {
154
                $path .= '/{id}';
155
            }
156
157
            $path .= '.{_format}';
158
        }
159
160
        $resourceRouteName = Inflector::pluralize(Inflector::tableize($resourceShortName));
161
        $routeName = sprintf('%s%s_%s', self::ROUTE_NAME_PREFIX, $resourceRouteName, $actionName);
162
163
        $route = new Route(
164
            $path,
165
            [
166
                '_controller' => $controller,
167
                '_format' => null,
168
                '_api_resource_class' => $resourceClass,
169
                sprintf('_api_%s_operation_name', $collection ? 'collection' : 'item') => $operationName,
170
            ],
171
            [],
172
            [],
173
            '',
174
            [],
175
            [$operation['method']]
176
        );
177
178
        $routeCollection->add($routeName, $route);
179
    }
180
}
181