Completed
Pull Request — master (#997)
by Antoine
04:25
created

IriConverter::getIriFromResourceClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 5
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\UrlGeneratorInterface;
16
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
17
use ApiPlatform\Core\Exception\InvalidArgumentException;
18
use ApiPlatform\Core\Exception\ItemNotFoundException;
19
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
20
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
21
use ApiPlatform\Core\Util\ClassInfoTrait;
22
use Symfony\Component\PropertyAccess\PropertyAccess;
23
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
24
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;
25
use Symfony\Component\Routing\RouterInterface;
26
27
/**
28
 * {@inheritdoc}
29
 *
30
 * @author Kévin Dunglas <[email protected]>
31
 */
32
final class IriConverter implements IriConverterInterface
33
{
34
    use ClassInfoTrait;
35
36
    private $propertyNameCollectionFactory;
37
    private $propertyMetadataFactory;
38
    private $itemDataProvider;
39
    private $routeNameResolver;
40
    private $router;
41
    private $propertyAccessor;
42
    private $itemIdentifiersExtractor;
43
44
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, ItemIdentifiersExtractorInterface $itemIdentifiersExtractor = null)
45
    {
46
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
47
        $this->propertyMetadataFactory = $propertyMetadataFactory;
48
        $this->itemDataProvider = $itemDataProvider;
49
        $this->routeNameResolver = $routeNameResolver;
50
        $this->router = $router;
51
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
52
53
        if (!$itemIdentifiersExtractor) {
54
            @trigger_error('Not injecting ItemIdentifiersExtractor is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3');
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
55
            $this->itemIdentifiersExtractor = new ItemIdentifiersExtractor($this->propertyNameCollectionFactory, $this->propertyMetadataFactory, $this->propertyAccessor);
56
        } else {
57
            $this->itemIdentifiersExtractor = $itemIdentifiersExtractor;
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, false);
90
91
        $identifiers = $this->generateIdentifiersUrl($this->itemIdentifiersExtractor->getIdentifiersFromItem($item));
92
93
        return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
100
    {
101
        try {
102
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, true), [], $referenceType);
103
        } catch (RoutingExceptionInterface $e) {
104
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
105
        }
106
    }
107
108
    /**
109
     * Generate the identifier url.
110
     *
111
     * @param array $identifiers
112
     *
113
     * @return string[]
114
     */
115
    private function generateIdentifiersUrl(array $identifiers): array
116
    {
117
        if (1 === count($identifiers)) {
118
            return [rawurlencode(array_values($identifiers)[0])];
119
        }
120
121
        foreach ($identifiers as $name => $value) {
122
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
123
        }
124
125
        return $identifiers;
126
    }
127
}
128