Completed
Pull Request — master (#1478)
by Antoine
21:31
created

ItemDataProvider::getItem()   D

Complexity

Conditions 9
Paths 20

Size

Total Lines 38
Code Lines 22

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 22
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\Identifier\Normalizer\IdentifierNormalizerInterface;
24
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
25
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
26
use Doctrine\Common\Persistence\ManagerRegistry;
27
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
28
use Doctrine\ORM\EntityManagerInterface;
29
use Doctrine\ORM\QueryBuilder;
30
31
/**
32
 * Item data provider for the Doctrine ORM.
33
 *
34
 * @author Kévin Dunglas <[email protected]>
35
 * @author Samuel ROZE <[email protected]>
36
 */
37
class ItemDataProvider implements ItemDataProviderInterface, RestrictedDataProviderInterface
38
{
39
    use IdentifierManagerTrait;
40
41
    private $managerRegistry;
42
    private $itemExtensions;
43
44
    /**
45
     * @param ManagerRegistry                        $managerRegistry
46
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
47
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
48
     * @param QueryItemExtensionInterface[]          $itemExtensions
49
     */
50 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...
51
    {
52
        $this->managerRegistry = $managerRegistry;
53
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
54
        $this->propertyMetadataFactory = $propertyMetadataFactory;
55
        $this->itemExtensions = $itemExtensions;
56
    }
57
58
    public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
59
    {
60
        return null !== $this->managerRegistry->getManagerForClass($resourceClass);
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     *
66
     * The context may contain a `fetch_data` key representing whether the value should be fetched by Doctrine or if we should return a reference.
67
     *
68
     * @throws RuntimeException
69
     */
70
    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = [])
71
    {
72
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
73
        $identifiers = null;
74
        if (true === ($context[IdentifierNormalizerInterface::HAS_IDENTIFIER_NORMALIZER] ?? false)) {
75
            $identifiers = $id;
76
        }
77
78
        if (null === $identifiers) {
79
            $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 72 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...
80
        }
81
82
        $fetchData = $context['fetch_data'] ?? true;
83
        if (!$fetchData && $manager instanceof EntityManagerInterface) {
84
            return $manager->getReference($resourceClass, $identifiers);
85
        }
86
87
        $repository = $manager->getRepository($resourceClass);
88
        if (!method_exists($repository, 'createQueryBuilder')) {
89
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
90
        }
91
92
        $queryBuilder = $repository->createQueryBuilder('o');
93
        $queryNameGenerator = new QueryNameGenerator();
94
        $doctrineClassMetadata = $manager->getClassMetadata($resourceClass);
95
96
        $this->addWhereForIdentifiers($identifiers, $queryBuilder, $doctrineClassMetadata);
97
98 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...
99
            $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
100
101
            if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName, $context)) {
0 ignored issues
show
Unused Code introduced by
The call to QueryResultItemExtension...rface::supportsResult() has too many arguments starting with $context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
102
                return $extension->getResult($queryBuilder, $resourceClass, $operationName, $context);
0 ignored issues
show
Unused Code introduced by
The call to QueryResultItemExtensionInterface::getResult() has too many arguments starting with $resourceClass.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
103
            }
104
        }
105
106
        return $queryBuilder->getQuery()->getOneOrNullResult();
107
    }
108
109
    /**
110
     * Add WHERE conditions to the query for one or more identifiers (simple or composite).
111
     *
112
     * @param array         $identifiers
113
     * @param QueryBuilder  $queryBuilder
114
     * @param ClassMetadata $classMetadata
115
     */
116
    private function addWhereForIdentifiers(array $identifiers, QueryBuilder $queryBuilder, ClassMetadata $classMetadata)
117
    {
118
        $alias = $queryBuilder->getRootAliases()[0];
119
        foreach ($identifiers as $identifier => $value) {
120
            $placeholder = ':id_'.$identifier;
121
            $expression = $queryBuilder->expr()->eq(
122
                "{$alias}.{$identifier}",
123
                $placeholder
124
            );
125
126
            $queryBuilder->andWhere($expression);
127
128
            $queryBuilder->setParameter($placeholder, $value, $classMetadata->getTypeOfField($identifier));
129
        }
130
    }
131
}
132