Completed
Push — master ( f1cbd3...96a412 )
by Kévin
03:19
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
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
65
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
66
            $resourceShortName = $resourceMetadata->getShortName();
67
68
            if (null === $resourceShortName) {
69
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
70
            }
71
72 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...
73
                foreach ($collectionOperations as $operationName => $operation) {
74
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, true);
75
                }
76
            }
77
78 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...
79
                foreach ($itemOperations as $operationName => $operation) {
80
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, false);
81
                }
82
            }
83
        }
84
85
        return $routeCollection;
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91
    public function supports($resource, $type = null)
92
    {
93
        return 'api_platform' === $type;
94
    }
95
96
    /**
97
     * Load external files.
98
     *
99
     * @param RouteCollection $routeCollection
100
     */
101
    private function loadExternalFiles(RouteCollection $routeCollection)
102
    {
103
        $routeCollection->addCollection($this->fileLoader->load('api.xml'));
104
105
        if (isset($this->formats['jsonld'])) {
106
            $routeCollection->addCollection($this->fileLoader->load('jsonld.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