Completed
Pull Request — master (#1478)
by Antoine
09:05 queued 06:02
created

IriConverter   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 140
Duplicated Lines 16.43 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

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

7 Methods

Rating   Name   Duplication   Size   Complexity  
A generateIdentifiersUrl() 0 12 3
A __construct() 0 17 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 $propertyNameCollectionFactory;
44
    private $propertyMetadataFactory;
45
    private $itemDataProvider;
46
    private $routeNameResolver;
47
    private $router;
48
    private $propertyAccessor;
49
    private $identifiersExtractor;
50
    private $identifierNormalizer;
51
52
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null, IdentifierNormalizerInterface $identifierNormalizer = null)
53
    {
54
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
55
        $this->propertyMetadataFactory = $propertyMetadataFactory;
56
        $this->itemDataProvider = $itemDataProvider;
57
        $this->routeNameResolver = $routeNameResolver;
58
        $this->router = $router;
59
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
60
        $this->identifierNormalizer = $identifierNormalizer;
61
62
        if (null === $identifiersExtractor) {
63
            @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);
64
            $this->identifiersExtractor = new IdentifiersExtractor($this->propertyNameCollectionFactory, $this->propertyMetadataFactory, $this->propertyAccessor);
65
        } else {
66
            $this->identifiersExtractor = $identifiersExtractor;
67
        }
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function getItemFromIri(string $iri, array $context = [])
74
    {
75
        try {
76
            $parameters = $this->router->match($iri);
77
        } catch (RoutingExceptionInterface $e) {
78
            throw new InvalidArgumentException(sprintf('No route matches "%s".', $iri), $e->getCode(), $e);
79
        }
80
81
        if (!isset($parameters['_api_resource_class'], $parameters['id'])) {
82
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
83
        }
84
85
        $identifiers = [];
86
87
        if ($this->identifierNormalizer) {
88
            $identifiers = $this->identifierNormalizer->normalize((string) $parameters['id'], $parameters['_api_resource_class']);
89
        }
90
91
        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...
92
            return $item;
93
        }
94
95
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
96
    }
97
98
    /**
99
     * {@inheritdoc}
100
     */
101
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
102
    {
103
        $resourceClass = $this->getObjectClass($item);
104
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
105
106
        try {
107
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));
108
109
            return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
110
        } catch (RuntimeException $e) {
111
            throw new InvalidArgumentException(sprintf(
112
                'Unable to generate an IRI for the item of type "%s"',
113
                $resourceClass
114
            ), $e->getCode(), $e);
115
        } catch (RoutingExceptionInterface $e) {
116
            throw new InvalidArgumentException(sprintf(
117
                'Unable to generate an IRI for the item of type "%s"',
118
                $resourceClass
119
            ), $e->getCode(), $e);
120
        }
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126 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...
127
    {
128
        try {
129
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
130
        } catch (RoutingExceptionInterface $e) {
131
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
132
        }
133
    }
134
135
    /**
136
     * {@inheritdoc}
137
     */
138 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...
139
    {
140
        try {
141
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $referenceType);
142
        } catch (RoutingExceptionInterface $e) {
143
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
144
        }
145
    }
146
147
    /**
148
     * {@inheritdoc}
149
     */
150 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...
151
    {
152
        try {
153
            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...
154
        } catch (RoutingExceptionInterface $e) {
155
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
156
        }
157
    }
158
159
    /**
160
     * Generate the identifier url.
161
     *
162
     * @param array $identifiers
163
     *
164
     * @return string[]
165
     */
166
    private function generateIdentifiersUrl(array $identifiers): array
167
    {
168
        if (1 === count($identifiers)) {
169
            return [rawurlencode((string) array_values($identifiers)[0])];
170
        }
171
172
        foreach ($identifiers as $name => $value) {
173
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
174
        }
175
176
        return $identifiers;
177
    }
178
}
179