Passed
Pull Request — master (#1478)
by Antoine
02:53
created

ItemDataProvider   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 92
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 13
dl 0
loc 92
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A supports() 0 3 1
A addWhereForIdentifiers() 0 13 2
D getItem() 0 37 9
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
    public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, array $itemExtensions = [])
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);
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
        foreach ($this->itemExtensions as $extension) {
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 ApiPlatform\Core\Bridge\...rface::supportsResult() has too many arguments starting with $context. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

101
            if ($extension instanceof QueryResultItemExtensionInterface && $extension->/** @scrutinizer ignore-call */ supportsResult($resourceClass, $operationName, $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. Please note the @ignore annotation hint above.

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

102
                return $extension->/** @scrutinizer ignore-call */ getResult($queryBuilder, $resourceClass, $operationName, $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. Please note the @ignore annotation hint above.

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