Completed
Pull Request — master (#737)
by Antoine
04:41
created

ItemDataProvider::getItem()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 31
Code Lines 17

Duplication

Lines 9
Ratio 29.03 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 9
loc 31
rs 6.7272
cc 7
eloc 17
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
namespace ApiPlatform\Core\Bridge\Doctrine\Orm;
13
14
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
15
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultItemExtensionInterface;
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator;
17
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
18
use ApiPlatform\Core\Exception\InvalidArgumentException;
19
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
20
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
21
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
22
use Doctrine\Common\Persistence\ManagerRegistry;
23
use Doctrine\Common\Persistence\ObjectManager;
24
use Doctrine\ORM\EntityManagerInterface;
25
use Doctrine\ORM\QueryBuilder;
26
27
/**
28
 * Item data provider for the Doctrine ORM.
29
 *
30
 * @author Kévin Dunglas <[email protected]>
31
 * @author Samuel ROZE <[email protected]>
32
 */
33
class ItemDataProvider implements ItemDataProviderInterface
34
{
35
    private $managerRegistry;
36
    private $propertyNameCollectionFactory;
37
    private $propertyMetadataFactory;
38
    private $itemExtensions;
39
40
    /**
41
     * @param ManagerRegistry                        $managerRegistry
42
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
43
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
44
     * @param QueryItemExtensionInterface[]          $itemExtensions
45
     */
46
    public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, array $itemExtensions = [])
47
    {
48
        $this->managerRegistry = $managerRegistry;
49
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
50
        $this->propertyMetadataFactory = $propertyMetadataFactory;
51
        $this->itemExtensions = $itemExtensions;
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    public function getItem(string $resourceClass, $id, string $operationName = null, bool $fetchData = false)
58
    {
59
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
60
        if (null === $manager) {
61
            throw new ResourceClassNotSupportedException();
62
        }
63
64
        $identifiers = $this->normalizeIdentifiers($id, $manager, $resourceClass);
65
66
        if (!$fetchData && $manager instanceof EntityManagerInterface) {
67
            return $manager->getReference($resourceClass, $identifiers);
68
        }
69
70
        $repository = $manager->getRepository($resourceClass);
71
        $queryBuilder = $repository->createQueryBuilder('o');
72
        $queryNameGenerator = new QueryNameGenerator();
73
74
        $this->addWhereForIdentifiers($identifiers, $queryBuilder);
75
76 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...
77
            $extension->applyToItem($queryBuilder, $queryNameGenerator, $resourceClass, $identifiers, $operationName);
78
79
            if ($extension instanceof QueryResultItemExtensionInterface) {
80
                if ($extension->supportsResult($resourceClass, $operationName)) {
81
                    return $extension->getResult($queryBuilder);
82
                }
83
            }
84
        }
85
86
        return $queryBuilder->getQuery()->getOneOrNullResult();
87
    }
88
89
    /**
90
     * Add WHERE conditions to the query for one or more identifiers (simple or composite).
91
     *
92
     * @param array        $identifiers
93
     * @param QueryBuilder $queryBuilder
94
     */
95
    private function addWhereForIdentifiers(array $identifiers, QueryBuilder $queryBuilder)
96
    {
97
        if (empty($identifiers)) {
98
            return;
99
        }
100
101
        foreach ($identifiers as $identifier => $value) {
102
            $placeholder = ':id_'.$identifier;
103
            $expression = $queryBuilder->expr()->eq(
104
                'o.'.$identifier,
105
                $placeholder
106
            );
107
108
            $queryBuilder->andWhere($expression);
109
110
            $queryBuilder->setParameter($placeholder, $value);
111
        }
112
    }
113
114
    /**
115
     * Transform and check the identifier, composite or not.
116
     *
117
     * @param int|string    $id
118
     * @param ObjectManager $manager
119
     * @param string        $resourceClass
120
     *
121
     * @return array
122
     */
123
    private function normalizeIdentifiers($id, ObjectManager $manager, string $resourceClass) : array
124
    {
125
        $identifierValues = [$id];
126
        $doctrineMetadataIdentifier = $manager->getClassMetadata($resourceClass)->getIdentifier();
127
128
        if (count($doctrineMetadataIdentifier) >= 2) {
129
            $identifiers = explode(';', $id);
130
            $identifiersMap = [];
131
132
            // first transform identifiers to a proper key/value array
133
            foreach ($identifiers as $identifier) {
134
                $keyValue = explode('=', $identifier);
135
                $identifiersMap[$keyValue[0]] = $keyValue[1];
136
            }
137
        }
138
139
        $identifiers = [];
140
        $i = 0;
141
142
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
143
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
144
145
            $identifier = $propertyMetadata->isIdentifier();
146
            if (null === $identifier || false === $identifier) {
147
                continue;
148
            }
149
150
            $identifier = $identifiersMap[$propertyName] ?? $identifierValues[$i] ?? null;
151
152
            if (null === $identifier) {
153
                throw new InvalidArgumentException(sprintf('Invalid identifier "%s".', $id));
154
            }
155
156
            $identifiers[$propertyName] = $identifier;
157
            ++$i;
158
        }
159
160
        return $identifiers;
161
    }
162
}
163