Completed
Push — master ( eb47c5...6cfc21 )
by Antoine
21s
created

ItemDataProvider::getItem()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 34
Code Lines 19

Duplication

Lines 7
Ratio 20.59 %

Importance

Changes 0
Metric Value
dl 7
loc 34
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 19
nc 6
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\Exception\ResourceClassNotSupportedException;
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
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
    /**
57
     * {@inheritdoc}
58
     *
59
     * The context may contain a `fetch_data` key representing whether the value should be fetched by Doctrine or if we should return a reference.
60
     *
61
     * @throws RuntimeException
62
     */
63
    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = [])
64
    {
65
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
66
        if (null === $manager) {
67
            throw new ResourceClassNotSupportedException();
68
        }
69
70
        $identifiers = $this->normalizeIdentifiers($id, $manager, $resourceClass);
71
72
        $fetchData = $context['fetch_data'] ?? true;
73
        if (!$fetchData && $manager instanceof EntityManagerInterface) {
74
            return $manager->getReference($resourceClass, $identifiers);
75
        }
76
77
        $repository = $manager->getRepository($resourceClass);
78
        if (!method_exists($repository, 'createQueryBuilder')) {
79
            throw new RuntimeException('The repository class must have a "createQueryBuilder" method.');
80
        }
81
82
        $queryBuilder = $repository->createQueryBuilder('o');
83
        $queryNameGenerator = new QueryNameGenerator();
84
85
        $this->addWhereForIdentifiers($identifiers, $queryBuilder);
86
87 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...
88
            $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName, $context);
89
90
            if ($extension instanceof QueryResultItemExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
91
                return $extension->getResult($queryBuilder);
92
            }
93
        }
94
95
        return $queryBuilder->getQuery()->getOneOrNullResult();
96
    }
97
98
    /**
99
     * Add WHERE conditions to the query for one or more identifiers (simple or composite).
100
     *
101
     * @param array        $identifiers
102
     * @param QueryBuilder $queryBuilder
103
     */
104
    private function addWhereForIdentifiers(array $identifiers, QueryBuilder $queryBuilder)
105
    {
106
        foreach ($identifiers as $identifier => $value) {
107
            $placeholder = ':id_'.$identifier;
108
            $expression = $queryBuilder->expr()->eq(
109
                'o.'.$identifier,
110
                $placeholder
111
            );
112
113
            $queryBuilder->andWhere($expression);
114
115
            $queryBuilder->setParameter($placeholder, $value);
116
        }
117
    }
118
}
119