Passed
Pull Request — 2.4 (#2766)
by
unknown
03:25
created

IriConverter::getIriFromItem()   B

Complexity

Conditions 8
Paths 45

Size

Total Lines 31
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 24
nc 45
nop 2
dl 0
loc 31
rs 8.4444
c 0
b 0
f 0
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\IdentifierConverterInterface;
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\HttpFoundation\RequestStack;
34
use Symfony\Component\PropertyAccess\PropertyAccess;
35
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
36
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;
37
use Symfony\Component\Routing\RouterInterface;
38
39
/**
40
 * {@inheritdoc}
41
 *
42
 * @author Kévin Dunglas <[email protected]>
43
 */
44
final class IriConverter implements IriConverterInterface
45
{
46
    use ClassInfoTrait;
47
    use OperationDataProviderTrait;
48
49
    private $routeNameResolver;
50
    private $router;
51
    private $identifiersExtractor;
52
    private $request;
53
54
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null, SubresourceDataProviderInterface $subresourceDataProvider = null, IdentifierConverterInterface $identifierConverter = null, RequestStack $requestStack)
55
    {
56
        $this->itemDataProvider = $itemDataProvider;
57
        $this->routeNameResolver = $routeNameResolver;
58
        $this->router = $router;
59
        $this->identifiersExtractor = $identifiersExtractor;
60
        $this->subresourceDataProvider = $subresourceDataProvider;
61
        $this->identifierConverter = $identifierConverter;
62
        $this->request = $requestStack->getMasterRequest();
63
64
        if (null === $identifiersExtractor) {
65
            @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);
66
            $this->identifiersExtractor = new IdentifiersExtractor($propertyNameCollectionFactory, $propertyMetadataFactory, $propertyAccessor ?? PropertyAccess::createPropertyAccessor());
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'])) {
82
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
83
        }
84
85
        if (isset($parameters['_api_collection_operation_name'])) {
86
            throw new InvalidArgumentException(sprintf('The iri "%s" references a collection not an item.', $iri));
87
        }
88
89
        $attributes = AttributesExtractor::extractAttributes($parameters);
90
91
        try {
92
            $identifiers = $this->extractIdentifiers($parameters, $attributes);
93
        } catch (InvalidIdentifierException $e) {
94
            throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
95
        }
96
97
        if ($this->identifierConverter) {
98
            $context[IdentifierConverterInterface::HAS_IDENTIFIER_CONVERTER] = true;
99
        }
100
101
        if (isset($attributes['subresource_operation_name'])) {
102
            if (($item = $this->getSubresourceData($identifiers, $attributes, $context)) && !\is_array($item)) {
103
                return $item;
104
            }
105
106
            throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
107
        }
108
109
        if ($item = $this->getItemData($identifiers, $attributes, $context)) {
110
            return $item;
111
        }
112
113
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
114
    }
115
116
    /**
117
     * {@inheritdoc}
118
     */
119
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
120
    {
121
        $resourceClass = $this->getObjectClass($item);
122
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
123
124
        try {
125
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item), $resourceClass);
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

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

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...
126
            $currentRouteParams = $this->request->attributes->get('_route_params');
127
            $pathVariables = $route = $this->router->getRouteCollection()->get($routeName)->compile()->getPathVariables();
0 ignored issues
show
Unused Code introduced by
The assignment to $route is dead and can be removed.
Loading history...
128
            if ($resourceClass === $this->request->attributes->get('_api_resource_class')) {
129
                $params = in_array('id', $pathVariables) ? ['id' => implode(';', $identifiers)] : [];
130
                foreach ($currentRouteParams as $paramName => $paramVal) {
131
                    if (in_array($paramName, $pathVariables) && !array_key_exists($paramName, $params)) {
132
                        $params[$paramName] = $paramVal;
133
                    }
134
                }
135
            } else {
136
                $params = ['id' => implode(';', $identifiers)];
137
            }
138
139
            return $this->router->generate($routeName, $params, $referenceType);
140
        } catch (RuntimeException $e) {
141
            throw new InvalidArgumentException(sprintf(
142
                'Unable to generate an IRI for the item of type "%s"',
143
                $resourceClass
144
            ), $e->getCode(), $e);
145
        } catch (RoutingExceptionInterface $e) {
146
            throw new InvalidArgumentException(sprintf(
147
                'Unable to generate an IRI for the item of type "%s"',
148
                $resourceClass
149
            ), $e->getCode(), $e);
150
        }
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
157
    {
158
        try {
159
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
160
        } catch (RoutingExceptionInterface $e) {
161
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
162
        }
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     */
168
    public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
169
    {
170
        try {
171
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $referenceType);
172
        } catch (RoutingExceptionInterface $e) {
173
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
174
        }
175
    }
176
177
    /**
178
     * {@inheritdoc}
179
     */
180
    public function getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
181
    {
182
        try {
183
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_identifiers'], $referenceType);
184
        } catch (RoutingExceptionInterface $e) {
185
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
186
        }
187
    }
188
189
    /**
190
     * Generate the identifier url.
191
     *
192
     * @throws InvalidArgumentException
193
     *
194
     * @return string[]
195
     */
196
    private function generateIdentifiersUrl(array $identifiers, string $resourceClass): array
197
    {
198
        if (0 === \count($identifiers)) {
199
            throw new InvalidArgumentException(sprintf(
200
                'No identifiers defined for resource of type "%s"',
201
                $resourceClass
202
            ));
203
        }
204
205
        if (1 === \count($identifiers)) {
206
            return [rawurlencode((string) reset($identifiers))];
207
        }
208
209
        foreach ($identifiers as $name => $value) {
210
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
211
        }
212
213
        return array_values($identifiers);
214
    }
215
}
216