Completed
Pull Request — master (#1478)
by Antoine
06:34
created

IriConverter   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 134
Duplicated Lines 17.16 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 10
dl 23
loc 134
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A generateIdentifiersUrl() 0 12 3
A __construct() 0 14 2
B getItemFromIri() 0 24 5
A getIriFromItem() 0 21 3
A getIriFromResourceClass() 8 8 2
A getItemIriFromResourceClass() 7 8 2
A getSubresourceIriFromResourceClass() 8 8 2

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\Api\IdentifiersExtractor;
17
use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
18
use ApiPlatform\Core\Api\IriConverterInterface;
19
use ApiPlatform\Core\Api\OperationType;
20
use ApiPlatform\Core\Api\UrlGeneratorInterface;
21
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
22
use ApiPlatform\Core\Exception\InvalidArgumentException;
23
use ApiPlatform\Core\Exception\ItemNotFoundException;
24
use ApiPlatform\Core\Exception\RuntimeException;
25
use ApiPlatform\Core\Identifier\IdentifierNormalizerInterface;
26
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
27
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
28
use ApiPlatform\Core\Util\ClassInfoTrait;
29
use Symfony\Component\PropertyAccess\PropertyAccess;
30
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
31
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;
32
use Symfony\Component\Routing\RouterInterface;
33
34
/**
35
 * {@inheritdoc}
36
 *
37
 * @author Kévin Dunglas <[email protected]>
38
 */
39
final class IriConverter implements IriConverterInterface
40
{
41
    use ClassInfoTrait;
42
43
    private $itemDataProvider;
44
    private $routeNameResolver;
45
    private $router;
46
    private $identifiersExtractor;
47
    private $identifierNormalizer;
48
49
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null, IdentifierNormalizerInterface $identifierNormalizer = null)
50
    {
51
        $this->itemDataProvider = $itemDataProvider;
52
        $this->routeNameResolver = $routeNameResolver;
53
        $this->router = $router;
54
        $this->identifierNormalizer = $identifierNormalizer;
55
56
        if (null === $identifiersExtractor) {
57
            @trigger_error('Not injecting ItemIdentifiersExtractor is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3', E_USER_DEPRECATED);
58
            $this->identifiersExtractor = new IdentifiersExtractor($propertyNameCollectionFactory, $propertyMetadataFactory, $propertyAccessor ?? PropertyAccess::createPropertyAccessor());
59
        } else {
60
            $this->identifiersExtractor = $identifiersExtractor;
61
        }
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function getItemFromIri(string $iri, array $context = [])
68
    {
69
        try {
70
            $parameters = $this->router->match($iri);
71
        } catch (RoutingExceptionInterface $e) {
72
            throw new InvalidArgumentException(sprintf('No route matches "%s".', $iri), $e->getCode(), $e);
73
        }
74
75
        if (!isset($parameters['_api_resource_class'], $parameters['id'])) {
76
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
77
        }
78
79
        $identifiers = [];
80
81
        if ($this->identifierNormalizer) {
82
            $identifiers = $this->identifierNormalizer->normalize((string) $parameters['id'], $parameters['_api_resource_class']);
83
        }
84
85
        if ($item = $this->itemDataProvider->getItem($parameters['_api_resource_class'], $parameters['id'], null, $context, $identifiers)) {
0 ignored issues
show
Unused Code introduced by
The call to ItemDataProviderInterface::getItem() has too many arguments starting with $identifiers.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
86
            return $item;
87
        }
88
89
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
90
    }
91
92
    /**
93
     * {@inheritdoc}
94
     */
95
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
96
    {
97
        $resourceClass = $this->getObjectClass($item);
98
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
99
100
        try {
101
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));
102
103
            return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
104
        } catch (RuntimeException $e) {
105
            throw new InvalidArgumentException(sprintf(
106
                'Unable to generate an IRI for the item of type "%s"',
107
                $resourceClass
108
            ), $e->getCode(), $e);
109
        } catch (RoutingExceptionInterface $e) {
110
            throw new InvalidArgumentException(sprintf(
111
                'Unable to generate an IRI for the item of type "%s"',
112
                $resourceClass
113
            ), $e->getCode(), $e);
114
        }
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 View Code Duplication
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
121
    {
122
        try {
123
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
124
        } catch (RoutingExceptionInterface $e) {
125
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
126
        }
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132 View Code Duplication
    public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
133
    {
134
        try {
135
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $referenceType);
136
        } catch (RoutingExceptionInterface $e) {
137
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
138
        }
139
    }
140
141
    /**
142
     * {@inheritdoc}
143
     */
144 View Code Duplication
    public function getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
145
    {
146
        try {
147
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_identifiers'], $referenceType);
0 ignored issues
show
Unused Code introduced by
The call to RouteNameResolverInterface::getRouteName() has too many arguments starting with $context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
148
        } catch (RoutingExceptionInterface $e) {
149
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
150
        }
151
    }
152
153
    /**
154
     * Generate the identifier url.
155
     *
156
     * @param array $identifiers
157
     *
158
     * @return string[]
159
     */
160
    private function generateIdentifiersUrl(array $identifiers): array
161
    {
162
        if (1 === \count($identifiers)) {
163
            return [rawurlencode((string) array_values($identifiers)[0])];
164
        }
165
166
        foreach ($identifiers as $name => $value) {
167
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
168
        }
169
170
        return $identifiers;
171
    }
172
}
173