Passed
Pull Request — master (#1837)
by Amrouche
03:01
created

IriConverter::getIriFromPlainIdentifier()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 14
nc 5
nop 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\OperationType;
20
use ApiPlatform\Core\Api\PlainIdentifierConverterInterface;
21
use ApiPlatform\Core\Api\UrlGeneratorInterface;
22
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
23
use ApiPlatform\Core\Exception\InvalidArgumentException;
24
use ApiPlatform\Core\Exception\ItemNotFoundException;
25
use ApiPlatform\Core\Exception\RuntimeException;
26
use ApiPlatform\Core\Identifier\Normalizer\ChainIdentifierDenormalizer;
27
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
28
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
29
use ApiPlatform\Core\Util\ClassInfoTrait;
30
use Symfony\Component\PropertyAccess\PropertyAccess;
31
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
32
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;
33
use Symfony\Component\Routing\RouterInterface;
34
35
/**
36
 * {@inheritdoc}
37
 *
38
 * @author Kévin Dunglas <[email protected]>
39
 */
40
final class IriConverter implements IriConverterInterface, PlainIdentifierConverterInterface
41
{
42
    use ClassInfoTrait;
43
44
    private $itemDataProvider;
45
    private $routeNameResolver;
46
    private $router;
47
    private $identifiersExtractor;
48
    private $identifierDenormalizer;
49
50
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null, ChainIdentifierDenormalizer $identifierDenormalizer = null)
51
    {
52
        $this->itemDataProvider = $itemDataProvider;
53
        $this->routeNameResolver = $routeNameResolver;
54
        $this->router = $router;
55
        $this->identifierDenormalizer = $identifierDenormalizer;
56
57
        if (null === $identifiersExtractor) {
58
            @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);
59
            $this->identifiersExtractor = new IdentifiersExtractor($propertyNameCollectionFactory, $propertyMetadataFactory, $propertyAccessor ?? PropertyAccess::createPropertyAccessor());
60
        } else {
61
            $this->identifiersExtractor = $identifiersExtractor;
62
        }
63
64
        if (null === $identifierDenormalizer) {
65
            @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);
66
        }
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function getItemFromIri(string $iri, array $context = [])
73
    {
74
        try {
75
            $parameters = $this->router->match($iri);
76
        } catch (RoutingExceptionInterface $e) {
77
            throw new InvalidArgumentException(sprintf('No route matches "%s".', $iri), $e->getCode(), $e);
78
        }
79
80
        if (!isset($parameters['_api_resource_class'], $parameters['id'])) {
81
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
82
        }
83
84
        $identifiers = $parameters['id'];
85
86
        if ($this->identifierDenormalizer) {
87
            $identifiers = $this->identifierDenormalizer->denormalize((string) $parameters['id'], $parameters['_api_resource_class']);
88
            $context[ChainIdentifierDenormalizer::HAS_IDENTIFIER_DENORMALIZER] = true;
89
        }
90
91
        if ($item = $this->itemDataProvider->getItem($parameters['_api_resource_class'], $identifiers, null, $context)) {
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 getIriFromPlainIdentifier($id, string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
102
    {
103
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
104
105
        try {
106
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromResourceClass($resourceClass));
107
108
            return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
109
        } catch (RuntimeException $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
        } catch (RoutingExceptionInterface $e) {
115
            throw new InvalidArgumentException(sprintf(
116
                'Unable to generate an IRI for the item of type "%s"',
117
                $resourceClass
118
            ), $e->getCode(), $e);
119
        }
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
126
    {
127
        $resourceClass = $this->getObjectClass($item);
128
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
129
130
        try {
131
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));
132
133
            return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
134
        } catch (RuntimeException $e) {
135
            throw new InvalidArgumentException(sprintf(
136
                'Unable to generate an IRI for the item of type "%s"',
137
                $resourceClass
138
            ), $e->getCode(), $e);
139
        } catch (RoutingExceptionInterface $e) {
140
            throw new InvalidArgumentException(sprintf(
141
                'Unable to generate an IRI for the item of type "%s"',
142
                $resourceClass
143
            ), $e->getCode(), $e);
144
        }
145
    }
146
147
    /**
148
     * {@inheritdoc}
149
     */
150
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
151
    {
152
        try {
153
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
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
     * {@inheritdoc}
161
     */
162
    public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
163
    {
164
        try {
165
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $referenceType);
166
        } catch (RoutingExceptionInterface $e) {
167
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
168
        }
169
    }
170
171
    /**
172
     * {@inheritdoc}
173
     */
174
    public function getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
175
    {
176
        try {
177
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_identifiers'], $referenceType);
178
        } catch (RoutingExceptionInterface $e) {
179
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
180
        }
181
    }
182
183
    /**
184
     * Generate the identifier url.
185
     *
186
     * @param array $identifiers
187
     *
188
     * @return string[]
189
     */
190
    private function generateIdentifiersUrl(array $identifiers): array
191
    {
192
        if (1 === \count($identifiers)) {
193
            return [rawurlencode((string) array_values($identifiers)[0])];
194
        }
195
196
        foreach ($identifiers as $name => $value) {
197
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
198
        }
199
200
        return $identifiers;
201
    }
202
}
203