Completed
Pull Request — 2.1 (#1480)
by Antoine
03:27
created

IriConverter::getIriFromResourceClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 8
Ratio 100 %

Importance

Changes 0
Metric Value
dl 8
loc 8
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 5
nc 2
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\Exception\InvalidArgumentException;
23
use ApiPlatform\Core\Exception\ItemNotFoundException;
24
use ApiPlatform\Core\Exception\RuntimeException;
25
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
26
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
27
use ApiPlatform\Core\Util\ClassInfoTrait;
28
use Symfony\Component\PropertyAccess\PropertyAccess;
29
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
30
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;
31
use Symfony\Component\Routing\RouterInterface;
32
33
/**
34
 * {@inheritdoc}
35
 *
36
 * @author Kévin Dunglas <[email protected]>
37
 */
38
final class IriConverter implements IriConverterInterface
39
{
40
    use ClassInfoTrait;
41
42
    private $propertyNameCollectionFactory;
43
    private $propertyMetadataFactory;
44
    private $itemDataProvider;
45
    private $routeNameResolver;
46
    private $router;
47
    private $propertyAccessor;
48
    private $identifiersExtractor;
49
50
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null)
51
    {
52
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
53
        $this->propertyMetadataFactory = $propertyMetadataFactory;
54
        $this->itemDataProvider = $itemDataProvider;
55
        $this->routeNameResolver = $routeNameResolver;
56
        $this->router = $router;
57
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
58
59
        if (null === $identifiersExtractor) {
60
            @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);
61
            $this->identifiersExtractor = new IdentifiersExtractor($this->propertyNameCollectionFactory, $this->propertyMetadataFactory, $this->propertyAccessor);
62
        } else {
63
            $this->identifiersExtractor = $identifiersExtractor;
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'], $parameters['id'])) {
79
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
80
        }
81
82
        if ($item = $this->itemDataProvider->getItem($parameters['_api_resource_class'], $parameters['id'], null, $context)) {
83
            return $item;
84
        }
85
86
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92
    public function getIdentifiersFromIri(string $iri, array $context = [])
93
    {
94
        return $this->identifiersExtractor->getIdentifiersFromItem($this->getItemFromIri($iri, $context));
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
101
    {
102
        $resourceClass = $this->getObjectClass($item);
103
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
104
105
        try {
106
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));
107
108
            return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
109
        } catch (RuntimeException $e) {
110
            throw new InvalidArgumentException(sprintf(
111
                'Unable to generate an IRI for the item of type "%s"',
112
                $resourceClass
113
            ), $e->getCode(), $e);
114
        } catch (RoutingExceptionInterface $e) {
115
            throw new InvalidArgumentException(sprintf(
116
                'Unable to generate an IRI for the item of type "%s"',
117
                $resourceClass
118
            ), $e->getCode(), $e);
119
        }
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125 View Code Duplication
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
    {
127
        try {
128
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
129
        } catch (RoutingExceptionInterface $e) {
130
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
131
        }
132
    }
133
134
    /**
135
     * {@inheritdoc}
136
     */
137 View Code Duplication
    public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
138
    {
139
        try {
140
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $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 View Code Duplication
    public function getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
150
    {
151
        try {
152
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_identifiers'], $referenceType);
0 ignored issues
show
Unused Code introduced by
The call to RouteNameResolverInterface::getRouteName() has too many arguments starting with $context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
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
     * Generate the identifier url.
160
     *
161
     * @param array $identifiers
162
     *
163
     * @return string[]
164
     */
165
    private function generateIdentifiersUrl(array $identifiers): array
166
    {
167
        if (1 === count($identifiers)) {
168
            return [rawurlencode((string) array_values($identifiers)[0])];
169
        }
170
171
        foreach ($identifiers as $name => $value) {
172
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
173
        }
174
175
        return $identifiers;
176
    }
177
}
178