Passed
Pull Request — 2.2 (#2051)
by
unknown
03:08
created

ChainItemDataProvider::getItem()   B

Complexity

Conditions 9
Paths 14

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.0555
c 0
b 0
f 0
cc 9
nc 14
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 && $identifier && \is_array($identifier)) {
49
                    if (\count($identifier) > 1) {
50
                        @trigger_error(sprintf('Receiving "$id" as non-array in an item data provider is deprecated in 2.3 in favor of implementing "%s".', DenormalizedIdentifiersAwareItemDataProviderInterface::class), E_USER_DEPRECATED);
51
                        $identifier = http_build_query($identifier, '', ';');
52
                    } else {
53
                        $identifier = current($identifier);
54
                    }
55
                }
56
57
                return $dataProvider->getItem($resourceClass, $identifier, $operationName, $context);
58
            } catch (ResourceClassNotSupportedException $e) {
59
                @trigger_error(sprintf('Throwing a "%s" is deprecated in favor of implementing "%s"', \get_class($e), RestrictedDataProviderInterface::class), E_USER_DEPRECATED);
60
                continue;
61
            }
62
        }
63
64
        return null;
65
    }
66
}
67