Completed
Pull Request — master (#1478)
by Antoine
07:00
created

ItemDataProvider::getItem()   D

Complexity

Conditions 9
Paths 20

Size

Total Lines 38
Code Lines 21

Duplication

Lines 7
Ratio 18.42 %

Importance

Changes 0
Metric Value
dl 7
loc 38
rs 4.909
c 0
b 0
f 0
cc 9
eloc 21
nc 20
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\Bridge\Doctrine\Orm;
15
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
17
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultItemExtensionInterface;
18
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\IdentifierManagerTrait;
19
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator;
20
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
21
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
22
use ApiPlatform\Core\Exception\RuntimeException;
23
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
24
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
25
use Doctrine\Common\Persistence\ManagerRegistry;
26
use Doctrine\ORM\EntityManagerInterface;
27
use Doctrine\ORM\QueryBuilder;
28
29
/**
30
 * Item data provider for the Doctrine ORM.
31
 *
32
 * @author Kévin Dunglas <[email protected]>
33
 * @author Samuel ROZE <[email protected]>
34
 */
35
class ItemDataProvider implements ItemDataProviderInterface, RestrictedDataProviderInterface
36
{
37
    use IdentifierManagerTrait;
38
39
    private $managerRegistry;
40
    private $itemExtensions;
41
42
    /**
43
     * @param ManagerRegistry                        $managerRegistry
44
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
45
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
46
     * @param QueryItemExtensionInterface[]          $itemExtensions
47
     */
48 View Code Duplication
    public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, array $itemExtensions = [])
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...
49
    {
50
        $this->managerRegistry = $managerRegistry;
51
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
52
        $this->propertyMetadataFactory = $propertyMetadataFactory;
53
        $this->itemExtensions = $itemExtensions;
54
    }
55
56
    public function supports(string $resourceClass, string $operationName = null): bool
57
    {
58
        return null !== $this->managerRegistry->getManagerForClass($resourceClass);
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     *
64
     * The context may contain a `fetch_data` key representing whether the value should be fetched by Doctrine or if we should return a reference.
65
     *
66
     * @throws RuntimeException
67
     */
68
    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []/** , array $identifiers **/)
69
    {
70
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
71
72
        $identifiers = null;
73
        if (5 === func_num_args()) {
74
            $identifiers = func_get_arg(4);
75
        }
76
77
        if (!$identifiers) {
78
            $identifiers = $this->normalizeIdentifiers($id, $manager, $resourceClass);
0 ignored issues
show
Bug introduced by
It seems like $manager defined by $this->managerRegistry->...orClass($resourceClass) on line 70 can be null; however, ApiPlatform\Core\Bridge\...:normalizeIdentifiers() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
79
        }
80
81
        $fetchData = $context['fetch_data'] ?? true;
82
        if (!$fetchData && $manager instanceof EntityManagerInterface) {
83
            return $manager->getReference($resourceClass, $identifiers);
84
        }
85
86
        $repository = $manager->getRepository($resourceClass);
87
        if (!method_exists($repository, 'createQueryBuilder')) {
88
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
89
        }
90
91
        $queryBuilder = $repository->createQueryBuilder('o');
92
        $queryNameGenerator = new QueryNameGenerator();
93
94
        $this->addWhereForIdentifiers($identifiers, $queryBuilder);
95
96 View Code Duplication
        foreach ($this->itemExtensions as $extension) {
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...
97
            $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
98
99
            if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
100
                return $extension->getResult($queryBuilder);
101
            }
102
        }
103
104
        return $queryBuilder->getQuery()->getOneOrNullResult();
105
    }
106
107
    /**
108
     * Add WHERE conditions to the query for one or more identifiers (simple or composite).
109
     *
110
     * @param array        $identifiers
111
     * @param QueryBuilder $queryBuilder
112
     */
113
    private function addWhereForIdentifiers(array $identifiers, QueryBuilder $queryBuilder)
114
    {
115
        foreach ($identifiers as $identifier => $value) {
116
            $placeholder = ':id_'.$identifier;
117
            $expression = $queryBuilder->expr()->eq(
118
                'o.'.$identifier,
119
                $placeholder
120
            );
121
122
            $queryBuilder->andWhere($expression);
123
124
            $queryBuilder->setParameter($placeholder, $value);
125
        }
126
    }
127
}
128