Passed
Pull Request — master (#1908)
by Ben
02:54
created

IriConverter::getItemFromIri()   C

Complexity

Conditions 8
Paths 11

Size

Total Lines 37
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 20
nc 11
nop 2
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\DataProvider\OperationDataProviderTrait;
23
use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface;
24
use ApiPlatform\Core\Exception\InvalidArgumentException;
25
use ApiPlatform\Core\Exception\InvalidIdentifierException;
26
use ApiPlatform\Core\Exception\ItemNotFoundException;
27
use ApiPlatform\Core\Exception\RuntimeException;
28
use ApiPlatform\Core\Identifier\Normalizer\ChainIdentifierDenormalizer;
29
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
30
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
31
use ApiPlatform\Core\Util\AttributesExtractor;
32
use ApiPlatform\Core\Util\ClassInfoTrait;
33
use Symfony\Component\PropertyAccess\PropertyAccess;
34
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
35
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;
36
use Symfony\Component\Routing\RouterInterface;
37
38
/**
39
 * {@inheritdoc}
40
 *
41
 * @author Kévin Dunglas <[email protected]>
42
 */
43
final class IriConverter implements IriConverterInterface
44
{
45
    use ClassInfoTrait;
46
    use OperationDataProviderTrait;
47
48
    private $routeNameResolver;
49
    private $router;
50
    private $identifiersExtractor;
51
52
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null, ChainIdentifierDenormalizer $identifierDenormalizer = null, SubresourceDataProviderInterface $subresourceDataProvider = null)
53
    {
54
        $this->itemDataProvider = $itemDataProvider;
55
        $this->routeNameResolver = $routeNameResolver;
56
        $this->router = $router;
57
        $this->identifiersExtractor = $identifiersExtractor;
58
        $this->identifierDenormalizer = $identifierDenormalizer;
59
        $this->subresourceDataProvider = $subresourceDataProvider;
60
61
        if (null === $identifiersExtractor) {
62
            @trigger_error(sprintf('Not injecting "%s" is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3', IdentifiersExtractorInterface::class), E_USER_DEPRECATED);
63
            $this->identifiersExtractor = new IdentifiersExtractor($propertyNameCollectionFactory, $propertyMetadataFactory, $propertyAccessor ?? PropertyAccess::createPropertyAccessor());
64
        }
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function getItemFromIri(string $iri, array $context = [])
71
    {
72
        try {
73
            $parameters = $this->router->match($iri);
74
        } catch (RoutingExceptionInterface $e) {
75
            throw new InvalidArgumentException(sprintf('No route matches "%s".', $iri), $e->getCode(), $e);
76
        }
77
78
        if (!isset($parameters['_api_resource_class'])) {
79
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
80
        }
81
82
        $attributes = AttributesExtractor::extractAttributes($parameters);
83
84
        try {
85
            $identifiers = $this->extractIdentifiers($parameters, $attributes);
86
        } catch (InvalidIdentifierException $e) {
87
            throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
88
        }
89
90
        if ($this->identifierDenormalizer) {
91
            $context[ChainIdentifierDenormalizer::HAS_IDENTIFIER_DENORMALIZER] = true;
92
        }
93
94
        if (isset($attributes['subresource_operation_name'])) {
95
            if ($item = $this->getSubresourceData($identifiers, $attributes, $context)) {
96
                return $item;
97
            }
98
99
            throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
100
        }
101
102
        if ($item = $this->getItemData($identifiers, $attributes, $context)) {
103
            return $item;
104
        }
105
106
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
107
    }
108
109
    /**
110
     * {@inheritdoc}
111
     */
112
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
113
    {
114
        $resourceClass = $this->getObjectClass($item);
115
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
116
117
        try {
118
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));
0 ignored issues
show
Bug introduced by
The method getIdentifiersFromItem() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

118
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->/** @scrutinizer ignore-call */ getIdentifiersFromItem($item));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
119
120
            return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
121
        } catch (RuntimeException $e) {
122
            throw new InvalidArgumentException(sprintf(
123
                'Unable to generate an IRI for the item of type "%s"',
124
                $resourceClass
125
            ), $e->getCode(), $e);
126
        } catch (RoutingExceptionInterface $e) {
127
            throw new InvalidArgumentException(sprintf(
128
                'Unable to generate an IRI for the item of type "%s"',
129
                $resourceClass
130
            ), $e->getCode(), $e);
131
        }
132
    }
133
134
    /**
135
     * {@inheritdoc}
136
     */
137
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
138
    {
139
        try {
140
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
141
        } catch (RoutingExceptionInterface $e) {
142
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
143
        }
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149
    public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
150
    {
151
        try {
152
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $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 getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
162
    {
163
        try {
164
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_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
     * Generate the identifier url.
172
     *
173
     * @param array $identifiers
174
     *
175
     * @return string[]
176
     */
177
    private function generateIdentifiersUrl(array $identifiers): array
178
    {
179
        if (1 === \count($identifiers)) {
180
            return [rawurlencode((string) array_values($identifiers)[0])];
181
        }
182
183
        foreach ($identifiers as $name => $value) {
184
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
185
        }
186
187
        return $identifiers;
188
    }
189
}
190