Passed
Pull Request — 2.2 (#1913)
by GRASSIOT
02:47
created

ChainItemDataProvider::getItem()   D

Complexity

Conditions 9
Paths 15

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 4.909
c 0
b 0
f 0
cc 9
eloc 15
nc 15
nop 4
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\DataProvider;
15
16
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
17
18
/**
19
 * Tries each configured data provider and returns the result of the first able to handle the resource class.
20
 *
21
 * @author Kévin Dunglas <[email protected]>
22
 */
23
final class ChainItemDataProvider implements ItemDataProviderInterface
24
{
25
    private $dataProviders;
26
27
    /**
28
     * @param ItemDataProviderInterface[] $dataProviders
29
     */
30
    public function __construct(/* iterable */ $dataProviders)
31
    {
32
        $this->dataProviders = $dataProviders;
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = [])
39
    {
40
        foreach ($this->dataProviders as $dataProvider) {
41
            try {
42
                if ($dataProvider instanceof RestrictedDataProviderInterface
43
                    && !$dataProvider->supports($resourceClass, $operationName, $context)) {
44
                    continue;
45
                }
46
47
                $identifier = $id;
48
                if (!$dataProvider instanceof DenormalizedIdentifiersAwareItemDataProviderInterface) {
49
                    @trigger_error(sprintf('Receiving "$id" as non-array in an item data provider is deprecated, your item data providers must implement "%s".', DenormalizedIdentifiersAwareItemDataProviderInterface::class), E_USER_DEPRECATED);
50
                    if ($identifier && \is_array($identifier)) {
51
                        $identifier = \count($identifier) > 1 ? http_build_query($identifier, '', ';') : current($identifier);
52
                    }
53
                }
54
55
                return $dataProvider->getItem($resourceClass, $identifier, $operationName, $context);
56
            } catch (ResourceClassNotSupportedException $e) {
57
                @trigger_error(sprintf('Throwing a "%s" is deprecated in favor of implementing "%s"', \get_class($e), RestrictedDataProviderInterface::class), E_USER_DEPRECATED);
58
                continue;
59
            }
60
        }
61
62
        return null;
63
    }
64
}
65