Completed
Pull Request — 2.1 (#1437)
by
unknown
02:44
created

IriConverter::getIriFromItem()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 21
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 16
nc 5
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
    const IRI_INTERNAL_PREFIX = '_api';
43
44
    private $propertyNameCollectionFactory;
45
    private $propertyMetadataFactory;
46
    private $itemDataProvider;
47
    private $routeNameResolver;
48
    private $router;
49
    private $propertyAccessor;
50
    private $identifiersExtractor;
51
52
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null)
53
    {
54
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
55
        $this->propertyMetadataFactory = $propertyMetadataFactory;
56
        $this->itemDataProvider = $itemDataProvider;
57
        $this->routeNameResolver = $routeNameResolver;
58
        $this->router = $router;
59
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
60
61
        if (null === $identifiersExtractor) {
62
            @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);
63
            $this->identifiersExtractor = new IdentifiersExtractor($this->propertyNameCollectionFactory, $this->propertyMetadataFactory, $this->propertyAccessor);
64
        } else {
65
            $this->identifiersExtractor = $identifiersExtractor;
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'], $parameters['id'])) {
81
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
82
        }
83
84
        if ($item = $this->itemDataProvider->getItem($parameters['_api_resource_class'], $parameters['id'], null, $context)) {
85
            return $item;
86
        }
87
88
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     */
94
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
95
    {
96
        $resourceClass = $this->getObjectClass($item);
97
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
98
99
        try {
100
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));
101
102
            return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
103
        } catch (RuntimeException $e) {
104
            throw new InvalidArgumentException(sprintf(
105
                'Unable to generate an IRI for the item of type "%s"',
106
                $resourceClass
107
            ), $e->getCode(), $e);
108
        } catch (RoutingExceptionInterface $e) {
109
            throw new InvalidArgumentException(sprintf(
110
                'Unable to generate an IRI for the item of type "%s"',
111
                $resourceClass
112
            ), $e->getCode(), $e);
113
        }
114
    }
115
116
    /**
117
     * {@inheritdoc}
118
     */
119 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...
120
    {
121
        try {
122
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
123
        } catch (RoutingExceptionInterface $e) {
124
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
125
        }
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     */
131 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...
132
    {
133
        try {
134
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $referenceType);
135
        } catch (RoutingExceptionInterface $e) {
136
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
137
        }
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143
    public function getContextIriFromShortName(string $shortName, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
144
    {
145
        return self::IRI_INTERNAL_PREFIX.$this->router->generate('api_jsonld_context', ['shortName' => $shortName], $referenceType);
146
    }
147
148
    /**
149
     * {@inheritdoc}
150
     */
151
    public function getApiDocIri(int $referenceType = UrlGeneratorInterface::ABS_PATH): string
152
    {
153
        return self::IRI_INTERNAL_PREFIX.$this->router->generate('api_doc', [], $referenceType);
154
    }
155
156
    /**
157
     * {@inheritdoc}
158
     */
159 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...
160
    {
161
        try {
162
            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...
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
     * Generate the identifier url.
170
     *
171
     * @param array $identifiers
172
     *
173
     * @return string[]
174
     */
175
    private function generateIdentifiersUrl(array $identifiers): array
176
    {
177
        if (1 === count($identifiers)) {
178
            return [rawurlencode((string) array_values($identifiers)[0])];
179
        }
180
181
        foreach ($identifiers as $name => $value) {
182
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
183
        }
184
185
        return $identifiers;
186
    }
187
}
188