Issues (332)

src/Bridge/Symfony/Routing/IriConverter.php (1 issue)

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\ResourceClassResolverInterface;
21
use ApiPlatform\Core\Api\UrlGeneratorInterface;
22
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
23
use ApiPlatform\Core\DataProvider\OperationDataProviderTrait;
24
use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface;
25
use ApiPlatform\Core\Exception\InvalidArgumentException;
26
use ApiPlatform\Core\Exception\InvalidIdentifierException;
27
use ApiPlatform\Core\Exception\ItemNotFoundException;
28
use ApiPlatform\Core\Exception\RuntimeException;
29
use ApiPlatform\Core\Identifier\IdentifierConverterInterface;
30
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
31
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
32
use ApiPlatform\Core\Util\AttributesExtractor;
33
use ApiPlatform\Core\Util\ResourceClassInfoTrait;
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 ResourceClassInfoTrait;
47
    use OperationDataProviderTrait;
48
49
    private $routeNameResolver;
50
    private $router;
51
    private $identifiersExtractor;
52
53
    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, ResourceClassResolverInterface $resourceClassResolver = null)
54
    {
55
        $this->itemDataProvider = $itemDataProvider;
56
        $this->routeNameResolver = $routeNameResolver;
57
        $this->router = $router;
58
        $this->identifiersExtractor = $identifiersExtractor;
59
        $this->subresourceDataProvider = $subresourceDataProvider;
60
        $this->identifierConverter = $identifierConverter;
61
        $this->resourceClassResolver = $resourceClassResolver;
62
63
        if (null === $identifiersExtractor) {
64
            @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);
65
            $this->identifiersExtractor = new IdentifiersExtractor($propertyNameCollectionFactory, $propertyMetadataFactory, $propertyAccessor ?? PropertyAccess::createPropertyAccessor());
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'])) {
81
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
82
        }
83
84
        if (isset($parameters['_api_collection_operation_name'])) {
85
            throw new InvalidArgumentException(sprintf('The iri "%s" references a collection not an item.', $iri));
86
        }
87
88
        $attributes = AttributesExtractor::extractAttributes($parameters);
89
90
        try {
91
            $identifiers = $this->extractIdentifiers($parameters, $attributes);
92
        } catch (InvalidIdentifierException $e) {
93
            throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
94
        }
95
96
        if ($this->identifierConverter) {
97
            $context[IdentifierConverterInterface::HAS_IDENTIFIER_CONVERTER] = true;
98
        }
99
100
        if (isset($attributes['subresource_operation_name'])) {
101
            if (($item = $this->getSubresourceData($identifiers, $attributes, $context)) && !\is_array($item)) {
102
                return $item;
103
            }
104
105
            throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
106
        }
107
108
        if ($item = $this->getItemData($identifiers, $attributes, $context)) {
109
            return $item;
110
        }
111
112
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
119
    {
120
        $resourceClass = $this->getResourceClass($item, true);
121
122
        try {
123
            $identifiers = $this->identifiersExtractor->getIdentifiersFromItem($item);
0 ignored issues
show
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

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