Completed
Push — master ( 62ffea...ad14ac )
by
unknown
03:12
created

ItemDataProvider::supports()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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
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 = [])
69
    {
70
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
71
72
        $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...
73
74
        $fetchData = $context['fetch_data'] ?? true;
75
        if (!$fetchData && $manager instanceof EntityManagerInterface) {
76
            return $manager->getReference($resourceClass, $identifiers);
77
        }
78
79
        $repository = $manager->getRepository($resourceClass);
80
        if (!method_exists($repository, 'createQueryBuilder')) {
81
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
82
        }
83
84
        $queryBuilder = $repository->createQueryBuilder('o');
85
        $queryNameGenerator = new QueryNameGenerator();
86
87
        $this->addWhereForIdentifiers($identifiers, $queryBuilder);
88
89 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...
90
            $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
91
92
            if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
93
                return $extension->getResult($queryBuilder);
94
            }
95
        }
96
97
        return $queryBuilder->getQuery()->getOneOrNullResult();
98
    }
99
100
    /**
101
     * Add WHERE conditions to the query for one or more identifiers (simple or composite).
102
     *
103
     * @param array        $identifiers
104
     * @param QueryBuilder $queryBuilder
105
     */
106
    private function addWhereForIdentifiers(array $identifiers, QueryBuilder $queryBuilder)
107
    {
108
        foreach ($identifiers as $identifier => $value) {
109
            $placeholder = ':id_'.$identifier;
110
            $expression = $queryBuilder->expr()->eq(
111
                'o.'.$identifier,
112
                $placeholder
113
            );
114
115
            $queryBuilder->andWhere($expression);
116
117
            $queryBuilder->setParameter($placeholder, $value);
118
        }
119
    }
120
}
121