Completed
Pull Request — master (#997)
by Antoine
03:23
created

IriConverter::generateIdentifiersUrl()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 6
nc 3
nop 1
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\UrlGeneratorInterface;
16
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
17
use ApiPlatform\Core\Exception\InvalidArgumentException;
18
use ApiPlatform\Core\Exception\ItemNotFoundException;
19
use ApiPlatform\Core\Exception\RuntimeException;
20
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
21
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
22
use ApiPlatform\Core\Util\ClassInfoTrait;
23
use Symfony\Component\PropertyAccess\PropertyAccess;
24
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
25
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;
26
use Symfony\Component\Routing\RouterInterface;
27
28
/**
29
 * {@inheritdoc}
30
 *
31
 * @author Kévin Dunglas <[email protected]>
32
 */
33
final class IriConverter implements IriConverterInterface
34
{
35
    use ClassInfoTrait;
36
    use IriConverterTrait;
37
38
    private $propertyNameCollectionFactory;
39
    private $propertyMetadataFactory;
40
    private $itemDataProvider;
41
    private $routeNameResolver;
42
    private $router;
43
    private $propertyAccessor;
44
45 View Code Duplication
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null)
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...
46
    {
47
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
48
        $this->propertyMetadataFactory = $propertyMetadataFactory;
49
        $this->itemDataProvider = $itemDataProvider;
50
        $this->routeNameResolver = $routeNameResolver;
51
        $this->router = $router;
52
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function getItemFromIri(string $iri, array $context = [])
59
    {
60
        try {
61
            $parameters = $this->router->match($iri);
62
        } catch (RoutingExceptionInterface $e) {
63
            throw new InvalidArgumentException(sprintf('No route matches "%s".', $iri), $e->getCode(), $e);
64
        }
65
66
        if (!isset($parameters['_api_resource_class'], $parameters['id'])) {
67
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
68
        }
69
70
        if ($item = $this->itemDataProvider->getItem($parameters['_api_resource_class'], $parameters['id'], null, $context)) {
71
            return $item;
72
        }
73
74
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 View Code Duplication
    public function getIriFromItem($item, 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...
81
    {
82
        $resourceClass = $this->getObjectClass($item);
83
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, false);
84
85
        $identifiers = $this->generateIdentifiersUrl($this->getIdentifiersFromItem($item));
86
87
        return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
94
    {
95
        try {
96
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, true), [], $referenceType);
97
        } catch (RoutingExceptionInterface $e) {
98
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
99
        }
100
    }
101
102
    /**
103
     * Find identifiers from an Item (Object).
104
     *
105
     * @param object $item
106
     *
107
     * @throws RuntimeException
108
     *
109
     * @return array
110
     */
111
    private function getIdentifiersFromItem($item): array
112
    {
113
        $identifiers = [];
114
        $resourceClass = $this->getObjectClass($item);
115
116 View Code Duplication
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
117
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
118
119
            $identifier = $propertyMetadata->isIdentifier();
120
            if (null === $identifier || false === $identifier) {
121
                continue;
122
            }
123
124
            $identifiers[$propertyName] = $this->propertyAccessor->getValue($item, $propertyName);
125
126
            if (!is_object($identifiers[$propertyName])) {
127
                continue;
128
            }
129
130
            $relatedResourceClass = $this->getObjectClass($identifiers[$propertyName]);
131
            $relatedItem = $identifiers[$propertyName];
132
133
            unset($identifiers[$propertyName]);
134
135
            foreach ($this->propertyNameCollectionFactory->create($relatedResourceClass) as $relatedPropertyName) {
136
                $propertyMetadata = $this->propertyMetadataFactory->create($relatedResourceClass, $relatedPropertyName);
137
138
                if ($propertyMetadata->isIdentifier()) {
139
                    if (isset($identifiers[$propertyName])) {
140
                        throw new RuntimeException(sprintf('Composite identifiers not supported in "%s" through relation "%s" of "%s" used as identifier', $relatedResourceClass, $propertyName, $resourceClass));
141
                    }
142
143
                    $identifiers[$propertyName] = $this->propertyAccessor->getValue($relatedItem, $relatedPropertyName);
144
                }
145
            }
146
147
            if (!isset($identifiers[$propertyName])) {
148
                throw new RuntimeException(sprintf('No identifier found in "%s" through relation "%s" of "%s" used as identifier', $relatedResourceClass, $propertyName, $resourceClass));
149
            }
150
        }
151
152
        return $identifiers;
153
    }
154
}
155