Completed
Push — 2.0 ( e69d85...2b1775 )
by Kévin
19s
created

IriConverter   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 144
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 22
lcom 1
cbo 12
dl 0
loc 144
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getItemFromIri() 0 18 4
A getIriFromItem() 0 9 1
A __construct() 0 9 2
A getIriFromResourceClass() 0 8 2
D getIdentifiersFromItem() 0 46 10
A generateIdentifiersUrl() 0 12 3
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\IriConverterInterface;
17
use ApiPlatform\Core\Api\UrlGeneratorInterface;
18
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
19
use ApiPlatform\Core\Exception\InvalidArgumentException;
20
use ApiPlatform\Core\Exception\ItemNotFoundException;
21
use ApiPlatform\Core\Exception\RuntimeException;
22
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
23
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
24
use ApiPlatform\Core\Util\ClassInfoTrait;
25
use Symfony\Component\PropertyAccess\PropertyAccess;
26
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
27
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;
28
use Symfony\Component\Routing\RouterInterface;
29
30
/**
31
 * {@inheritdoc}
32
 *
33
 * @author Kévin Dunglas <[email protected]>
34
 */
35
final class IriConverter implements IriConverterInterface
36
{
37
    use ClassInfoTrait;
38
39
    private $propertyNameCollectionFactory;
40
    private $propertyMetadataFactory;
41
    private $itemDataProvider;
42
    private $routeNameResolver;
43
    private $router;
44
    private $propertyAccessor;
45
46
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null)
47
    {
48
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
49
        $this->propertyMetadataFactory = $propertyMetadataFactory;
50
        $this->itemDataProvider = $itemDataProvider;
51
        $this->routeNameResolver = $routeNameResolver;
52
        $this->router = $router;
53
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function getItemFromIri(string $iri, array $context = [])
60
    {
61
        try {
62
            $parameters = $this->router->match($iri);
63
        } catch (RoutingExceptionInterface $e) {
64
            throw new InvalidArgumentException(sprintf('No route matches "%s".', $iri), $e->getCode(), $e);
65
        }
66
67
        if (!isset($parameters['_api_resource_class'], $parameters['id'])) {
68
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
69
        }
70
71
        if ($item = $this->itemDataProvider->getItem($parameters['_api_resource_class'], $parameters['id'], null, $context)) {
72
            return $item;
73
        }
74
75
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
76
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
82
    {
83
        $resourceClass = $this->getObjectClass($item);
84
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, false);
85
86
        $identifiers = $this->generateIdentifiersUrl($this->getIdentifiersFromItem($item));
87
88
        return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     */
94
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
95
    {
96
        try {
97
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, true), [], $referenceType);
98
        } catch (RoutingExceptionInterface $e) {
99
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
100
        }
101
    }
102
103
    /**
104
     * Find identifiers from an Item (Object).
105
     *
106
     * @param object $item
107
     *
108
     * @throws RuntimeException
109
     *
110
     * @return array
111
     */
112
    private function getIdentifiersFromItem($item): array
113
    {
114
        $identifiers = [];
115
        $resourceClass = $this->getObjectClass($item);
116
117
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
118
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
119
120
            $identifier = $propertyMetadata->isIdentifier();
121
            if (null === $identifier || false === $identifier) {
122
                continue;
123
            }
124
125
            $identifier = $identifiers[$propertyName] = $this->propertyAccessor->getValue($item, $propertyName);
126
127
            if (!is_object($identifier)) {
128
                continue;
129
            } elseif (method_exists($identifier, '__toString')) {
130
                $identifiers[$propertyName] = (string) $identifier;
131
                continue;
132
            }
133
134
            $relatedResourceClass = $this->getObjectClass($identifier);
135
            $relatedItem = $identifier;
136
137
            unset($identifiers[$propertyName]);
138
139
            foreach ($this->propertyNameCollectionFactory->create($relatedResourceClass) as $relatedPropertyName) {
140
                $propertyMetadata = $this->propertyMetadataFactory->create($relatedResourceClass, $relatedPropertyName);
141
142
                if ($propertyMetadata->isIdentifier()) {
143
                    if (isset($identifiers[$propertyName])) {
144
                        throw new RuntimeException(sprintf('Composite identifiers not supported in "%s" through relation "%s" of "%s" used as identifier', $relatedResourceClass, $propertyName, $resourceClass));
145
                    }
146
147
                    $identifiers[$propertyName] = $this->propertyAccessor->getValue($relatedItem, $relatedPropertyName);
148
                }
149
            }
150
151
            if (!isset($identifiers[$propertyName])) {
152
                throw new RuntimeException(sprintf('No identifier found in "%s" through relation "%s" of "%s" used as identifier', $relatedResourceClass, $propertyName, $resourceClass));
153
            }
154
        }
155
156
        return $identifiers;
157
    }
158
159
    /**
160
     * Generate the identifier url.
161
     *
162
     * @param array $identifiers
163
     *
164
     * @return string[]
165
     */
166
    private function generateIdentifiersUrl(array $identifiers): array
167
    {
168
        if (1 === count($identifiers)) {
169
            return [rawurlencode((string) array_values($identifiers)[0])];
170
        }
171
172
        foreach ($identifiers as $name => $value) {
173
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
174
        }
175
176
        return $identifiers;
177
    }
178
}
179