Completed
Pull Request — master (#498)
by Antoine
05:11 queued 01:54
created

ApiLoader   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 106
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 12
c 2
b 0
f 0
lcom 1
cbo 11
dl 0
loc 106
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B load() 0 22 4
A supports() 0 4 1
B addRoute() 0 43 6
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\RuntimeException;
15
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
16
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
17
use Doctrine\Common\Inflector\Inflector;
18
use Symfony\Component\Config\FileLocator;
19
use Symfony\Component\Config\Loader\Loader;
20
use Symfony\Component\HttpKernel\KernelInterface;
21
use Symfony\Component\Routing\Loader\XmlFileLoader;
22
use Symfony\Component\Routing\Route;
23
use Symfony\Component\Routing\RouteCollection;
24
25
/**
26
 * Loads Resources.
27
 *
28
 * @author Kévin Dunglas <[email protected]>
29
 */
30
final class ApiLoader extends Loader
31
{
32
    const ROUTE_NAME_PREFIX = 'api_';
33
    const DEFAULT_ACTION_PATTERN = 'api_platform.action.';
34
35
    private $fileLoader;
36
    private $resourceNameCollectionFactory;
37
    private $resourceMetadataFactory;
38
39
    public function __construct(KernelInterface $kernel, ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory)
40
    {
41
        $this->fileLoader = new XmlFileLoader(new FileLocator($kernel->locateResource('@ApiPlatformBundle/Resources/config/routing')));
42
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
43
        $this->resourceMetadataFactory = $resourceMetadataFactory;
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function load($data, $type = null)
50
    {
51
        $routeCollection = new RouteCollection();
52
53
        $routeCollection->addCollection($this->fileLoader->load('jsonld.xml'));
54
        $routeCollection->addCollection($this->fileLoader->load('hydra.xml'));
55
56
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
57
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
58
            $normalizedShortName = Inflector::pluralize(Inflector::tableize($resourceMetadata->getShortName()));
59
60
            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...
61
                $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $normalizedShortName, true);
62
            }
63
64
            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...
65
                $this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $normalizedShortName, false);
66
            }
67
        }
68
69
        return $routeCollection;
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function supports($resource, $type = null)
76
    {
77
        return 'api_platform' === $type;
78
    }
79
80
    /**
81
     * Creates and adds a route for the given operation to the route collection.
82
     *
83
     * @param RouteCollection $routeCollection
84
     * @param string          $resourceClass
85
     * @param string          $operationName
86
     * @param array           $operation
87
     * @param string          $normalizedShortName
88
     * @param bool            $collection
89
     *
90
     * @throws RuntimeException
91
     */
92
    private function addRoute(RouteCollection $routeCollection, string $resourceClass, string $operationName, array $operation, string $normalizedShortName, bool $collection)
93
    {
94
        if (isset($operation['route_name'])) {
95
            return;
96
        }
97
98
        if (!isset($operation['method'])) {
99
            throw new RuntimeException('Either a "route_name" or a "method" operation attribute must exist.');
100
        }
101
102
        $collectionString = $collection ? 'collection' : 'item';
103
104
        $actionName = sprintf('%s_%s', $operationName, $collectionString);
105
        $controller = $operation['controller'] ?? self::DEFAULT_ACTION_PATTERN.sprintf('%s_%s', strtolower($operation['method']), $collectionString);
106
107
        $path = $operation['path'] ?? null;
108
109
        if (null === $path) {
110
            $path = '/'.$normalizedShortName;
111
112
            if (!$collection) {
113
                $path .= '/{id}';
114
            }
115
        }
116
117
        $routeName = sprintf('%s%s_%s', self::ROUTE_NAME_PREFIX, $normalizedShortName, $actionName);
118
119
        $route = new Route(
120
            $path,
121
            [
122
                '_controller' => $controller,
123
                '_resource_class' => $resourceClass,
124
                sprintf('_%s_operation_name', $collectionString) => $operationName,
125
            ],
126
            [],
127
            [],
128
            '',
129
            [],
130
            [$operation['method']]
131
        );
132
133
        $routeCollection->add($routeName, $route);
134
    }
135
}
136