Completed
Pull Request — master (#550)
by Antoine
03:20
created

IriConverter::getIriFromItem()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
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
namespace ApiPlatform\Core\Bridge\Symfony\Routing;
13
14
use ApiPlatform\Core\Api\IriConverterInterface;
15
use ApiPlatform\Core\Api\ItemDataProviderInterface;
16
use ApiPlatform\Core\Api\UrlGeneratorInterface;
17
use ApiPlatform\Core\Exception\InvalidArgumentException;
18
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
19
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
20
use ApiPlatform\Core\Util\ClassInfoTrait;
21
use Symfony\Component\PropertyAccess\PropertyAccess;
22
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
23
use Symfony\Component\Routing\Exception\ExceptionInterface;
24
use Symfony\Component\Routing\RouterInterface;
25
26
/**
27
 * {@inheritdoc}
28
 *
29
 * @author Kévin Dunglas <[email protected]>
30
 */
31
final class IriConverter implements IriConverterInterface
32
{
33
    use ClassInfoTrait;
34
35
    private $propertyNameCollectionFactory;
36
    private $propertyMetadataFactory;
37
    private $itemDataProvider;
38
    private $router;
39
    private $propertyAccessor;
40
41
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null)
42
    {
43
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
44
        $this->propertyMetadataFactory = $propertyMetadataFactory;
45
        $this->itemDataProvider = $itemDataProvider;
46
        $this->router = $router;
47
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function getItemFromIri(string $iri, bool $fetchData = false)
54
    {
55
        try {
56
            $parameters = $this->router->match($iri);
57
        } catch (ExceptionInterface $exception) {
58
            throw new InvalidArgumentException(sprintf('No route matches "%s".', $iri), $exception->getCode(), $exception);
59
        }
60
61
        if (!isset($parameters['_resource_class']) || !isset($parameters['id'])) {
62
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
63
        }
64
65
        if ($item = $this->itemDataProvider->getItem($parameters['_resource_class'], $parameters['id'], null, $fetchData)) {
66
            return $item;
67
        }
68
69
        throw new InvalidArgumentException(sprintf('Item not found for "%s".', $iri));
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH) : string
76
    {
77
        $resourceClass = $this->getObjectClass($item);
78
        $routeName = $this->getRouteName($resourceClass, false);
79
80
        $identifiers = array_map([$this, 'generateIdentifiersUrl'], $this->getIdentifiersFromItem($item));
81
82
        if (count($identifiers) > 1) {
83
            $identifiers = array_map(function ($identifierName, $identifierValue) {
84
                return sprintf('%s=%s', $identifierName, rawurlencode($identifierValue));
85
            }, array_keys($identifiers), $identifiers);
86
        }
87
88
        return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
89
    }
90
91
    /**
92
     * Get the identifier url.
93
     *
94
     * @param mixed $identifiers
95
     *
96
     * @return string
97
     */
98
    public function generateIdentifiersUrl($identifiers) : string
99
    {
100
        if (!is_array($identifiers)) {
101
            return rawurlencode($identifiers);
102
        }
103
104
        if (1 === count($identifiers)) {
105
            return rawurlencode(array_values($identifiers)[0]);
106
        }
107
108
        return array_map(function ($identifierName, $identifierValue) {
109
            return sprintf('%s=%s', $identifierName, $this->generateIdentifiersUrl($identifierValue));
110
        }, array_keys($identifiers), $identifiers);
111
    }
112
113
    /**
114
     * Find identifiers from an Item (Object).
115
     *
116
     * @param object $item
117
     *
118
     * @throws RuntimeException
119
     *
120
     * @return array
121
     */
122
    private function getIdentifiersFromItem($item) : array
123
    {
124
        $identifiers = [];
125
        $resourceClass = $this->getObjectClass($item);
126
127
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
128
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
129
130
            if ($propertyMetadata->isIdentifier()) {
131
                $identifiers[$propertyName] = $this->propertyAccessor->getValue($item, $propertyName);
132
133
                if (!is_object($identifiers[$propertyName])) {
134
                    continue;
135
                }
136
137
                $identifiers[$propertyName] = $this->getIdentifiersFromItem($identifiers[$propertyName]);
138
139
                if (0 === count($identifiers[$propertyName])) {
140
                    throw new \RuntimeException(sprintf('%s identifiers can not be found', $resourceClass));
141
                }
142
            }
143
        }
144
145
        return $identifiers;
146
    }
147
148
    /**
149
     * {@inheritdoc}
150
     */
151
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH) : string
152
    {
153
        try {
154
            return $this->router->generate($this->getRouteName($resourceClass, true), [], $referenceType);
155
        } catch (ExceptionInterface $e) {
156
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
157
        }
158
    }
159
160
    /**
161
     * Finds the route name for this resource.
162
     *
163
     * @param string $resourceClass
164
     * @param bool   $collection
165
     *
166
     * @throws InvalidArgumentException
167
     *
168
     * @return string
169
     */
170
    private function getRouteName(string $resourceClass, bool $collection) : string
171
    {
172
        $operationType = $collection ? 'collection' : 'item';
173
174
        foreach ($this->router->getRouteCollection()->all() as $routeName => $route) {
175
            $currentResourceClass = $route->getDefault('_resource_class');
176
            $operation = $route->getDefault(sprintf('_%s_operation_name', $operationType));
177
            $methods = $route->getMethods();
178
179
            if ($resourceClass === $currentResourceClass && null !== $operation && (empty($methods) || in_array('GET', $methods))) {
180
                $found = true;
181
                break;
182
            }
183
        }
184
185
        if (!isset($found)) {
186
            throw new InvalidArgumentException(sprintf('No route associated with the type "%s".', $resourceClass));
187
        }
188
189
        return $routeName;
0 ignored issues
show
Bug introduced by
The variable $routeName seems to be defined by a foreach iteration on line 174. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
190
    }
191
}
192