Completed
Push — 2.2 ( 654e42...cc34af )
by Antoine
16s queued 10s
created

IriConverter::getIriFromResourceClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
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 $itemDataProvider;
43
    private $routeNameResolver;
44
    private $router;
45
    private $identifiersExtractor;
46
47
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null)
48
    {
49
        $this->itemDataProvider = $itemDataProvider;
50
        $this->routeNameResolver = $routeNameResolver;
51
        $this->router = $router;
52
53
        if (null === $identifiersExtractor) {
54
            @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);
55
            $this->identifiersExtractor = new IdentifiersExtractor($propertyNameCollectionFactory, $propertyMetadataFactory, $propertyAccessor ?? PropertyAccess::createPropertyAccessor());
56
        } else {
57
            $this->identifiersExtractor = $identifiersExtractor;
58
        }
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function getItemFromIri(string $iri, array $context = [])
65
    {
66
        try {
67
            $parameters = $this->router->match($iri);
68
        } catch (RoutingExceptionInterface $e) {
69
            throw new InvalidArgumentException(sprintf('No route matches "%s".', $iri), $e->getCode(), $e);
70
        }
71
72
        if (!isset($parameters['_api_resource_class'], $parameters['id'])) {
73
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
74
        }
75
76
        if ($item = $this->itemDataProvider->getItem($parameters['_api_resource_class'], $parameters['id'], null, $context)) {
77
            return $item;
78
        }
79
80
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
87
    {
88
        $resourceClass = $this->getObjectClass($item);
89
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);
90
91
        try {
92
            $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));
93
94
            return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
95
        } catch (RuntimeException $e) {
96
            throw new InvalidArgumentException(sprintf(
97
                'Unable to generate an IRI for the item of type "%s"',
98
                $resourceClass
99
            ), $e->getCode(), $e);
100
        } catch (RoutingExceptionInterface $e) {
101
            throw new InvalidArgumentException(sprintf(
102
                'Unable to generate an IRI for the item of type "%s"',
103
                $resourceClass
104
            ), $e->getCode(), $e);
105
        }
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
112
    {
113
        try {
114
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
115
        } catch (RoutingExceptionInterface $e) {
116
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
117
        }
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
124
    {
125
        try {
126
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $referenceType);
127
        } catch (RoutingExceptionInterface $e) {
128
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
129
        }
130
    }
131
132
    /**
133
     * {@inheritdoc}
134
     */
135
    public function getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
136
    {
137
        try {
138
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_identifiers'], $referenceType);
139
        } catch (RoutingExceptionInterface $e) {
140
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
141
        }
142
    }
143
144
    /**
145
     * Generate the identifier url.
146
     *
147
     * @param array $identifiers
148
     *
149
     * @return string[]
150
     */
151
    private function generateIdentifiersUrl(array $identifiers): array
152
    {
153
        if (1 === \count($identifiers)) {
154
            return [rawurlencode((string) array_values($identifiers)[0])];
155
        }
156
157
        foreach ($identifiers as $name => $value) {
158
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
159
        }
160
161
        return $identifiers;
162
    }
163
}
164