Completed
Pull Request — master (#611)
by Kévin
04:43 queued 01:28
created

ApiLoader   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 135
Duplicated Lines 7.41 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 21
lcom 1
cbo 14
dl 10
loc 135
rs 10
c 2
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
C load() 10 32 8
A supports() 0 4 1
C addRoute() 0 58 11

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
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
44
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, ResourcePathNamingStrategyInterface $resourcePathGenerator, ContainerInterface $container)
45
    {
46
        $this->fileLoader = new XmlFileLoader(new FileLocator($kernel->locateResource('@ApiPlatformBundle/Resources/config/routing')));
47
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
48
        $this->resourceMetadataFactory = $resourceMetadataFactory;
49
        $this->resourcePathGenerator = $resourcePathGenerator;
50
        $this->container = $container;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function load($data, $type = null)
57
    {
58
        $routeCollection = new RouteCollection();
59
60
        $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
61
        $routeCollection->addCollection($this->fileLoader->load('hydra.xml'));
62
        if ($this->container->getParameter('api_platform.enable_swagger')) {
63
            $routeCollection->addCollection($this->fileLoader->load('swagger.xml'));
64
        }
65
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
66
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
67
            $resourceShortName = $resourceMetadata->getShortName();
68
69
            if (null === $resourceShortName) {
70
                throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
71
            }
72
73 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...
74
                foreach ($collectionOperations as $operationName => $operation) {
75
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, true);
76
                }
77
            }
78
79 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...
80
                foreach ($itemOperations as $operationName => $operation) {
81
                    $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceShortName, false);
82
                }
83
            }
84
        }
85
86
        return $routeCollection;
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92
    public function supports($resource, $type = null)
93
    {
94
        return 'api_platform' === $type;
95
    }
96
97
    /**
98
     * Creates and adds a route for the given operation to the route collection.
99
     *
100
     * @param RouteCollection $routeCollection
101
     * @param string          $resourceClass
102
     * @param string          $operationName
103
     * @param array           $operation
104
     * @param string          $resourceShortName
105
     * @param bool            $collection
106
     *
107
     * @throws RuntimeException
108
     */
109
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $resourceShortName, bool $collection)
110
    {
111
        if (isset($operation['route_name'])) {
112
            return;
113
        }
114
115
        if (!isset($operation['method'])) {
116
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
117
        }
118
119
        $controller = $operation['controller'] ?? null;
120
        $collectionType = $collection ? 'collection' : 'item';
121
        $actionName = sprintf('%s_%s', strtolower($operation['method']), $collectionType);
122
123
        if (null === $controller) {
124
            $controller = self::DEFAULT_ACTION_PATTERN.$actionName;
125
126
            if (!$this->container->has($controller)) {
127
                throw new RuntimeException(sprintf('There is no builtin action for the %s %s operation. You need to define the controller yourself.', $collectionType, $operation['method']));
128
            }
129
        }
130
131
        if ($operationName !== strtolower($operation['method'])) {
132
            $actionName = sprintf('%s_%s', $operationName, $collection ? 'collection' : 'item');
133
        }
134
135
        $path = $operation['path'] ?? null;
136
137
        if (null === $path) {
138
            $path = '/'.$this->resourcePathGenerator->generateResourceBasePath($resourceShortName);
139
140
            if (!$collection) {
141
                $path .= '/{id}';
142
            }
143
144
            $path .= '.{_format}';
145
        }
146
147
        $resourceRouteName = Inflector::pluralize(Inflector::tableize($resourceShortName));
148
        $routeName = sprintf('%s%s_%s', self::ROUTE_NAME_PREFIX, $resourceRouteName, $actionName);
149
150
        $route = new Route(
151
            $path,
152
            [
153
                '_controller' => $controller,
154
                '_format' => null,
155
                '_api_resource_class' => $resourceClass,
156
                sprintf('_api_%s_operation_name', $collection ? 'collection' : 'item') => $operationName,
157
            ],
158
            [],
159
            [],
160
            '',
161
            [],
162
            [$operation['method']]
163
        );
164
165
        $routeCollection->add($routeName, $route);
166
    }
167
}
168