Completed
Pull Request — master (#458)
by Théo
02:53
created

ItemDataProvider::fallbackGetItem()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
rs 9.2
cc 4
eloc 10
nc 3
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\Api\ItemDataProviderInterface;
15
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
16
use ApiPlatform\Core\Exception\InvalidArgumentException;
17
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
18
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
19
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
20
use Doctrine\Common\Persistence\ManagerRegistry;
21
use Doctrine\Common\Persistence\ObjectManager;
22
use Doctrine\ORM\EntityManagerInterface;
23
use Doctrine\ORM\EntityRepository;
24
use Doctrine\ORM\QueryBuilder;
25
26
/**
27
 * Item data provider for the Doctrine ORM.
28
 *
29
 * @author Kévin Dunglas <[email protected]>
30
 * @author Samuel ROZE <[email protected]>
31
 * @author Théo FIDRY <[email protected]>
32
 */
33
class ItemDataProvider implements ItemDataProviderInterface
34
{
35
    private $managerRegistry;
36
    private $propertyNameCollectionFactory;
37
    private $propertyMetadataFactory;
38
    private $itemExtensions;
39
    private $decoratedProvider;
40
41
    /**
42
     * @param ManagerRegistry                        $managerRegistry
43
     * @param PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory
44
     * @param PropertyMetadataFactoryInterface       $propertyMetadataFactory
45
     * @param QueryItemExtensionInterface[]          $itemExtensions
46
     * @param ItemDataProviderInterface|null         $decoratedProvider
47
     */
48
    public function __construct(
49
        ManagerRegistry $managerRegistry,
50
        PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory,
51
        PropertyMetadataFactoryInterface $propertyMetadataFactory,
52
        array $itemExtensions = [],
53
        ItemDataProviderInterface $decoratedProvider = null
54
    ) {
55
        $this->managerRegistry = $managerRegistry;
56
        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
57
        $this->propertyMetadataFactory = $propertyMetadataFactory;
58
        $this->itemExtensions = $itemExtensions;
59
        $this->decoratedProvider = $decoratedProvider;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function getItem(string $resourceClass, $id, string $operationName = null, bool $fetchData = false)
66
    {
67
        if (null !== $this->decoratedProvider) {
68
            try {
69
                return $this->decoratedProvider->getItem($resourceClass, $id, $operationName, $fetchData);
70
            } catch (ResourceClassNotSupportedException $resourceClassNotSupportedException) {
71
                // Ignore it
72
            }
73
        }
74
75
        return $this->fallbackGetItem($resourceClass, $id, $operationName, $fetchData);
76
    }
77
78
    /**
79
     * @param string      $resourceClass
80
     * @param int|string  $id
81
     * @param string|null $operationName
82
     * @param bool        $fetchData
83
     *
84
     * @return object
85
     * @throws ResourceClassNotSupportedException
86
     */
87
    private function fallbackGetItem(string $resourceClass, $id, string $operationName = null, bool $fetchData = false)
88
    {
89
        $manager = $this->getManagerForClass($resourceClass);
90
        $identifiers = $this->getIdentifiers($resourceClass, $id);
91
92
        if (!$fetchData || $manager instanceof EntityManagerInterface) {
93
            return $manager->getReference($resourceClass, $identifiers);
94
        }
95
96
        $queryBuilder = $this->retrieveQueryBuilder($manager, $resourceClass);
97
        $this->applyIdentifiersToQueryBuilder($queryBuilder, $identifiers);
98
99
        foreach ($this->itemExtensions as $extension) {
100
            $extension->applyToItem($queryBuilder, $resourceClass, $identifiers, $operationName);
101
        }
102
103
        return $queryBuilder->getQuery()->getOneOrNullResult();
104
    }
105
106
    /**
107
     * @param string $resourceClass
108
     *
109
     * @return ObjectManager
110
     * @throws ResourceClassNotSupportedException
111
     */
112
    private function getManagerForClass(string $resourceClass)
113
    {
114
        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
115
        if (null !== $manager) {
116
            return $manager;
117
        }
118
119
        throw new ResourceClassNotSupportedException();
120
    }
121
122
    /**
123
     * @param string $resourceClass
124
     * @param int|string $id
125
     *
126
     * @return array Identifier values with keys as property names
127
     */
128
    private function getIdentifiers(string $resourceClass, $id)
129
    {
130
        $identifierValues = explode('-', $id);
131
        $identifiers = [];
132
        $i = 0;
133
134
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
135
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
136
137
            $identifier = $propertyMetadata->isIdentifier();
138
            if (null === $identifier || false === $identifier) {
139
                continue;
140
            }
141
142
            if (!isset($identifierValues[$i])) {
143
                throw new InvalidArgumentException(sprintf('Invalid identifier "%s".', $id));
144
            }
145
146
            $identifiers[$propertyName] = $identifierValues[$i];
147
            ++$i;
148
        }
149
150
        return $identifiers;
151
    }
152
153
    /**
154
     * @param ObjectManager $resourceManager
155
     * @param string        $resourceClass
156
     *
157
     * @return \Doctrine\ORM\QueryBuilder
158
     */
159
    private function retrieveQueryBuilder(ObjectManager $resourceManager, string $resourceClass)
160
    {
161
        $repository = $resourceManager->getRepository($resourceClass);
162
163
        if ($repository instanceof  EntityRepository) {
164
            return $repository->createQueryBuilder('o');
165
        }
166
167
        if ($resourceManager instanceof EntityManagerInterface) {
168
            // TODO: check if $resourceClass is good here
169
            return $resourceManager->createQueryBuilder()
170
                ->select('o')
171
                ->from($resourceClass, 'o');
172
        }
173
174
        // TODO: handle this case
175
    }
176
177
    private function applyIdentifiersToQueryBuilder(QueryBuilder $queryBuilder, array $identifiers)
178
    {
179
        foreach ($identifiers as $propertyName => $value) {
180
            $placeholder = 'id_'.$propertyName;
181
182
            $queryBuilder
183
                ->where($queryBuilder->expr()->eq('o.'.$propertyName, ':'.$placeholder))
184
                ->setParameter($placeholder, $value);
185
        }
186
    }
187
}
188