Passed
Pull Request — master (#1837)
by Amrouche
02:58
created

IriConverter   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 159
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 24
dl 0
loc 159
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
B getItemFromIri() 0 24 5
A getIriFromResourceClass() 0 6 2
A __construct() 0 16 3
A getSubresourceIriFromResourceClass() 0 6 2
A getIriFromPlainIdentifier() 0 16 4
A getItemIriFromResourceClass() 0 6 2
A getIriFromItem() 0 19 3
A generateIdentifiersUrl() 0 11 3
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\IriPlainIdentifierAwareConverterInterface;
20
use ApiPlatform\Core\Api\OperationType;
21
use ApiPlatform\Core\Api\PlainIdentifierConverterInterface;
0 ignored issues
show
Bug introduced by
The type ApiPlatform\Core\Api\Pla...ifierConverterInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
use ApiPlatform\Core\Api\UrlGeneratorInterface;
23
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
24
use ApiPlatform\Core\Exception\InvalidArgumentException;
25
use ApiPlatform\Core\Exception\ItemNotFoundException;
26
use ApiPlatform\Core\Exception\RuntimeException;
27
use ApiPlatform\Core\Identifier\Normalizer\ChainIdentifierDenormalizer;
28
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
29
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
30
use ApiPlatform\Core\Util\ClassInfoTrait;
31
use Symfony\Component\PropertyAccess\PropertyAccess;
32
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
33
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;
34
use Symfony\Component\Routing\RouterInterface;
35
36
/**
37
 * {@inheritdoc}
38
 *
39
 * @author Kévin Dunglas <[email protected]>
40
 */
41
final class IriConverter implements IriPlainIdentifierAwareConverterInterface
42
{
43
    use ClassInfoTrait;
44
45
    private $itemDataProvider;
46
    private $routeNameResolver;
47
    private $router;
48
    private $identifiersExtractor;
49
    private $identifierDenormalizer;
50
51
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null, ChainIdentifierDenormalizer $identifierDenormalizer = null)
52
    {
53
        $this->itemDataProvider = $itemDataProvider;
54
        $this->routeNameResolver = $routeNameResolver;
55
        $this->router = $router;
56
        $this->identifierDenormalizer = $identifierDenormalizer;
57
58
        if (null === $identifiersExtractor) {
59
            @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);
60
            $this->identifiersExtractor = new IdentifiersExtractor($propertyNameCollectionFactory, $propertyMetadataFactory, $propertyAccessor ?? PropertyAccess::createPropertyAccessor());
61
        } else {
62
            $this->identifiersExtractor = $identifiersExtractor;
63
        }
64
65
        if (null === $identifierDenormalizer) {
66
            @trigger_error(sprintf('Not injecting "%s" is deprecated since API Platform 2.2 and will not be possible anymore in API Platform 3.', ChainIdentifierDenormalizer::class), E_USER_DEPRECATED);
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 = $parameters['id'];
86
87
        if ($this->identifierDenormalizer) {
88
            $identifiers = $this->identifierDenormalizer->denormalize((string) $parameters['id'], $parameters['_api_resource_class']);
89
            $context[ChainIdentifierDenormalizer::HAS_IDENTIFIER_DENORMALIZER] = true;
90
        }
91
92
        if ($item = $this->itemDataProvider->getItem($parameters['_api_resource_class'], $identifiers, null, $context)) {
93
            return $item;
94
        }
95
96
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function getIriFromPlainIdentifier($id, string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
103
    {
104
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
105
106
        try {
107
            return $this->router->generate($routeName, ['id' => \is_array($id) ? implode(';', $id) : $id], $referenceType);
108
        } catch (RuntimeException $e) {
109
            throw new InvalidArgumentException(sprintf(
110
                'Unable to generate an IRI for the item of type "%s"',
111
                $resourceClass
112
            ), $e->getCode(), $e);
113
        } catch (RoutingExceptionInterface $e) {
114
            throw new InvalidArgumentException(sprintf(
115
                'Unable to generate an IRI for the item of type "%s"',
116
                $resourceClass
117
            ), $e->getCode(), $e);
118
        }
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
125
    {
126
        $resourceClass = $this->getObjectClass($item);
127
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
128
129
        try {
130
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));
131
132
            return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
133
        } catch (RuntimeException $e) {
134
            throw new InvalidArgumentException(sprintf(
135
                'Unable to generate an IRI for the item of type "%s"',
136
                $resourceClass
137
            ), $e->getCode(), $e);
138
        } catch (RoutingExceptionInterface $e) {
139
            throw new InvalidArgumentException(sprintf(
140
                'Unable to generate an IRI for the item of type "%s"',
141
                $resourceClass
142
            ), $e->getCode(), $e);
143
        }
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
150
    {
151
        try {
152
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
153
        } catch (RoutingExceptionInterface $e) {
154
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
155
        }
156
    }
157
158
    /**
159
     * {@inheritdoc}
160
     */
161
    public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
162
    {
163
        try {
164
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $referenceType);
165
        } catch (RoutingExceptionInterface $e) {
166
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
167
        }
168
    }
169
170
    /**
171
     * {@inheritdoc}
172
     */
173
    public function getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
174
    {
175
        try {
176
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_identifiers'], $referenceType);
177
        } catch (RoutingExceptionInterface $e) {
178
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
179
        }
180
    }
181
182
    /**
183
     * Generate the identifier url.
184
     *
185
     * @param array $identifiers
186
     *
187
     * @return string[]
188
     */
189
    private function generateIdentifiersUrl(array $identifiers): array
190
    {
191
        if (1 === \count($identifiers)) {
192
            return [rawurlencode((string) array_values($identifiers)[0])];
193
        }
194
195
        foreach ($identifiers as $name => $value) {
196
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
197
        }
198
199
        return $identifiers;
200
    }
201
}
202