Completed
Pull Request — 2.0 (#1078)
by Claudio
03:09
created

IriConverter::getIdentifiersFromItem()   D

Complexity

Conditions 10
Paths 11

Size

Total Lines 46
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 4.983
c 0
b 0
f 0
cc 10
eloc 26
nc 11
nop 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
A IriConverter::getItemIriFromResourceClass() 7 8 2
A IriConverter::getSubresourceIriFromResourceClass() 8 8 2
A IriConverter::generateIdentifiersUrl() 0 12 3

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
25
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
26
use ApiPlatform\Core\Util\ClassInfoTrait;
27
use Symfony\Component\PropertyAccess\PropertyAccess;
28
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
29
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;
30
use Symfony\Component\Routing\RouterInterface;
31
32
/**
33
 * {@inheritdoc}
34
 *
35
 * @author Kévin Dunglas <[email protected]>
36
 */
37
final class IriConverter implements IriConverterInterface
38
{
39
    use ClassInfoTrait;
40
41
    private $propertyNameCollectionFactory;
42
    private $propertyMetadataFactory;
43
    private $itemDataProvider;
44
    private $routeNameResolver;
45
    private $router;
46
    private $propertyAccessor;
47
    private $identifiersExtractor;
48
49
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null)
50
    {
51
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
52
        $this->propertyMetadataFactory = $propertyMetadataFactory;
53
        $this->itemDataProvider = $itemDataProvider;
54
        $this->routeNameResolver = $routeNameResolver;
55
        $this->router = $router;
56
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
57
58
        if (null === $identifiersExtractor) {
59
            @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...
60
            $this->identifiersExtractor = new IdentifiersExtractor($this->propertyNameCollectionFactory, $this->propertyMetadataFactory, $this->propertyAccessor);
61
        } else {
62
            $this->identifiersExtractor = $identifiersExtractor;
63
        }
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function getItemFromIri(string $iri, array $context = [])
70
    {
71
        try {
72
            $parameters = $this->router->match($iri);
73
        } catch (RoutingExceptionInterface $e) {
74
            throw new InvalidArgumentException(sprintf('No route matches "%s".', $iri), $e->getCode(), $e);
75
        }
76
77
        if (!isset($parameters['_api_resource_class'], $parameters['id'])) {
78
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
79
        }
80
81
        if ($item = $this->itemDataProvider->getItem($parameters['_api_resource_class'], $parameters['id'], null, $context)) {
82
            return $item;
83
        }
84
85
        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91
    public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
92
    {
93
        $resourceClass = $this->getObjectClass($item);
94
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, false);
95
96
        $identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));
97
98
        return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
99
    }
100
101
    /**
102
     * {@inheritdoc}
103
     */
104 View Code Duplication
    public function getIriFromResourceClass(string $resourceClass, 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...
105
    {
106
        try {
107
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
108
        } catch (RoutingExceptionInterface $e) {
109
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
110
        }
111
    }
112
113
    /**
114
     * {@inheritdoc}
115
     */
116 View Code Duplication
    public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, 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...
117
    {
118
        try {
119
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM), $identifiers, $referenceType);
120
        } catch (RoutingExceptionInterface $e) {
121
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
122
        }
123
    }
124
125
    /**
126
     * {@inheritdoc}
127
     */
128 View Code Duplication
    public function getSubresourceIriFromResourceClass(string $resourceClass, array $identifiers, 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...
129
    {
130
        try {
131
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE), $identifiers, $referenceType);
132
        } catch (RoutingExceptionInterface $e) {
133
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
134
        }
135
    }
136
137
    /**
138
     * Generate the identifier url.
139
     *
140
     * @param array $identifiers
141
     *
142
     * @return string[]
143
     */
144
    private function generateIdentifiersUrl(array $identifiers): array
145
    {
146
        if (1 === count($identifiers)) {
147
            return [rawurlencode((string) array_values($identifiers)[0])];
148
        }
149
150
        foreach ($identifiers as $name => $value) {
151
            $identifiers[$name] = sprintf('%s=%s', $name, $value);
152
        }
153
154
        return $identifiers;
155
    }
156
}
157