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

IriConverter::getIriFromPlainIdentifier()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.2
c 0
b 0
f 0
cc 4
eloc 13
nc 3
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\IriToIdentifierConverterInterface;
20
use ApiPlatform\Core\Api\OperationType;
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 IriToIdentifierConverterInterface, IriConverterInterface
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
            return $this->router->generate($routeName, ['id' => \is_array($id) ? implode(';', $id) : $id], $referenceType);
107
        } catch (RuntimeException $e) {
108
            throw new InvalidArgumentException(sprintf(
109
                'Unable to generate an IRI for the item of type "%s"',
110
                $resourceClass
111
            ), $e->getCode(), $e);
112
        } catch (RoutingExceptionInterface $e) {
113
            throw new InvalidArgumentException(sprintf(
114
                'Unable to generate an IRI for the item of type "%s"',
115
                $resourceClass
116
            ), $e->getCode(), $e);
117
        }
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
124
    {
125
        $resourceClass = $this->getObjectClass($item);
126
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
127
128
        try {
129
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));
130
131
            return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
132
        } catch (RuntimeException $e) {
133
            throw new InvalidArgumentException(sprintf(
134
                'Unable to generate an IRI for the item of type "%s"',
135
                $resourceClass
136
            ), $e->getCode(), $e);
137
        } catch (RoutingExceptionInterface $e) {
138
            throw new InvalidArgumentException(sprintf(
139
                'Unable to generate an IRI for the item of type "%s"',
140
                $resourceClass
141
            ), $e->getCode(), $e);
142
        }
143
    }
144
145
    /**
146
     * {@inheritdoc}
147
     */
148
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
149
    {
150
        try {
151
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
152
        } catch (RoutingExceptionInterface $e) {
153
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
154
        }
155
    }
156
157
    /**
158
     * {@inheritdoc}
159
     */
160
    public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
161
    {
162
        try {
163
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $referenceType);
164
        } catch (RoutingExceptionInterface $e) {
165
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
166
        }
167
    }
168
169
    /**
170
     * {@inheritdoc}
171
     */
172
    public function getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
173
    {
174
        try {
175
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_identifiers'], $referenceType);
176
        } catch (RoutingExceptionInterface $e) {
177
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
178
        }
179
    }
180
181
    /**
182
     * Generate the identifier url.
183
     *
184
     * @param array $identifiers
185
     *
186
     * @return string[]
187
     */
188
    private function generateIdentifiersUrl(array $identifiers): array
189
    {
190
        if (1 === \count($identifiers)) {
191
            return [rawurlencode((string) array_values($identifiers)[0])];
192
        }
193
194
        foreach ($identifiers as $name => $value) {
195
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
196
        }
197
198
        return $identifiers;
199
    }
200
}
201