Passed
Pull Request — master (#1837)
by Amrouche
02:57
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\IriPlainIdentifierAwareConverterInterface;
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\Normalizer\ChainIdentifierDenormalizer;
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 IriPlainIdentifierAwareConverterInterface
40
{
41
    use ClassInfoTrait;
42
43
    private $itemDataProvider;
44
    private $routeNameResolver;
45
    private $router;
46
    private $identifiersExtractor;
47
    private $identifierDenormalizer;
48
49
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null, ChainIdentifierDenormalizer $identifierDenormalizer = null)
50
    {
51
        $this->itemDataProvider = $itemDataProvider;
52
        $this->routeNameResolver = $routeNameResolver;
53
        $this->router = $router;
54
        $this->identifierDenormalizer = $identifierDenormalizer;
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
        if (null === $identifierDenormalizer) {
64
            @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);
65
        }
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function getItemFromIri(string $iri, array $context = [])
72
    {
73
        try {
74
            $parameters = $this->router->match($iri);
75
        } catch (RoutingExceptionInterface $e) {
76
            throw new InvalidArgumentException(sprintf('No route matches "%s".', $iri), $e->getCode(), $e);
77
        }
78
79
        if (!isset($parameters['_api_resource_class'], $parameters['id'])) {
80
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
81
        }
82
83
        $identifiers = $parameters['id'];
84
85
        if ($this->identifierDenormalizer) {
86
            $identifiers = $this->identifierDenormalizer->denormalize((string) $parameters['id'], $parameters['_api_resource_class']);
87
            $context[ChainIdentifierDenormalizer::HAS_IDENTIFIER_DENORMALIZER] = true;
88
        }
89
90
        if ($item = $this->itemDataProvider->getItem($parameters['_api_resource_class'], $identifiers, null, $context)) {
91
            return $item;
92
        }
93
94
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function getIriFromPlainIdentifier($id, string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
101
    {
102
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
103
104
        try {
105
            return $this->router->generate($routeName, ['id' => \is_array($id) ? implode(';', $id) : $id], $referenceType);
106
        } catch (RuntimeException $e) {
107
            throw new InvalidArgumentException(sprintf(
108
                'Unable to generate an IRI for the item of type "%s"',
109
                $resourceClass
110
            ), $e->getCode(), $e);
111
        } catch (RoutingExceptionInterface $e) {
112
            throw new InvalidArgumentException(sprintf(
113
                'Unable to generate an IRI for the item of type "%s"',
114
                $resourceClass
115
            ), $e->getCode(), $e);
116
        }
117
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
123
    {
124
        $resourceClass = $this->getObjectClass($item);
125
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
126
127
        try {
128
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));
129
130
            return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
131
        } catch (RuntimeException $e) {
132
            throw new InvalidArgumentException(sprintf(
133
                'Unable to generate an IRI for the item of type "%s"',
134
                $resourceClass
135
            ), $e->getCode(), $e);
136
        } catch (RoutingExceptionInterface $e) {
137
            throw new InvalidArgumentException(sprintf(
138
                'Unable to generate an IRI for the item of type "%s"',
139
                $resourceClass
140
            ), $e->getCode(), $e);
141
        }
142
    }
143
144
    /**
145
     * {@inheritdoc}
146
     */
147
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
148
    {
149
        try {
150
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
151
        } catch (RoutingExceptionInterface $e) {
152
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
153
        }
154
    }
155
156
    /**
157
     * {@inheritdoc}
158
     */
159
    public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
160
    {
161
        try {
162
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $referenceType);
163
        } catch (RoutingExceptionInterface $e) {
164
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
165
        }
166
    }
167
168
    /**
169
     * {@inheritdoc}
170
     */
171
    public function getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
172
    {
173
        try {
174
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_identifiers'], $referenceType);
175
        } catch (RoutingExceptionInterface $e) {
176
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
177
        }
178
    }
179
180
    /**
181
     * Generate the identifier url.
182
     *
183
     * @param array $identifiers
184
     *
185
     * @return string[]
186
     */
187
    private function generateIdentifiersUrl(array $identifiers): array
188
    {
189
        if (1 === \count($identifiers)) {
190
            return [rawurlencode((string) array_values($identifiers)[0])];
191
        }
192
193
        foreach ($identifiers as $name => $value) {
194
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
195
        }
196
197
        return $identifiers;
198
    }
199
}
200