Completed
Push — 2.0 ( e69d85...2b1775 )
by Kévin
19s
created

ApiLoader   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 143
Duplicated Lines 3.5 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 15
dl 5
loc 143
rs 9.1666
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A supports() 0 4 1
A loadExternalFiles() 0 8 2
C addRoute() 0 48 9
C load() 5 32 8

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