-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathTreeObjectHydrator.php
More file actions
318 lines (265 loc) · 8.84 KB
/
Copy pathTreeObjectHydrator.php
File metadata and controls
318 lines (265 loc) · 8.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
<?php
/*
* This file is part of the Doctrine Behavioral Extensions package.
* (c) Gediminas Morkevicius <gediminas.morkevicius@gmail.com> http://www.gediminasm.org
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Gedmo\Tree\Hydrator\ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Internal\Hydration\ObjectHydrator;
use Doctrine\ORM\Mapping\OneToManyAssociationMapping;
use Doctrine\ORM\PersistentCollection;
use Gedmo\Exception\InvalidMappingException;
use Gedmo\Tool\ORM\Hydration\EntityManagerRetriever;
use Gedmo\Tool\ORM\Hydration\HydratorCompat;
use Gedmo\Tree\TreeListener;
/**
* Automatically maps the parent and children properties of Tree nodes
*
* @author Ilija Tovilo <ilija.tovilo@me.com>
*
* @final since gedmo/doctrine-extensions 3.11
*/
class TreeObjectHydrator extends ObjectHydrator
{
use EntityManagerRetriever;
use HydratorCompat;
private const NO_PARENT_ID = '__no-parent__';
/**
* @var array<string, mixed>
*/
private $config = [];
/**
* @var string
*/
private $idField;
/**
* @var string
*/
private $parentField;
/**
* @var string
*/
private $childrenField;
/**
* @param object $object
* @param string $property
* @param mixed $value
*
* @return void
*/
public function setPropertyValue($object, $property, $value)
{
$meta = $this->getEntityManager()->getClassMetadata(get_class($object));
$meta->setFieldValue($object, $property, $value);
}
/**
* We hook into the `hydrateAllData` to map the children collection of the entity
*
* @return array<int, object>
*/
protected function doHydrateAllData()
{
$data = parent::hydrateAllData();
if ([] === $data) {
return $data;
}
$listener = $this->getTreeListener($this->getEntityManager());
$entityClass = $this->getEntityClassFromHydratedData($data);
$this->config = $listener->getConfiguration($this->getEntityManager(), $entityClass);
$this->idField = $this->getIdField($entityClass);
$this->parentField = $this->getParentField();
$this->childrenField = $this->getChildrenField($entityClass);
$childrenHashmap = $this->buildChildrenHashmap($data);
$this->populateChildrenArray($data, $childrenHashmap);
// Only return root elements or elements who's parents haven't been fetched
// The sub-nodes will be accessible via the `children` property
return $this->getRootNodes($data);
}
/**
* Creates a hashmap to quickly find the children of a node
*
* ```
* [parentId => [child1, child2, ...], ...]
* ```
*
* @param array<int, object> $nodes
*
* @return array<int|string, array<int, object>>
*/
protected function buildChildrenHashmap($nodes)
{
$r = [];
foreach ($nodes as $node) {
$parentProxy = $this->getPropertyValue($node, $this->config['parent']);
$parentId = self::NO_PARENT_ID;
if (null !== $parentProxy) {
$parentId = $this->getPropertyValue($parentProxy, $this->idField);
}
$r[$parentId][] = $node;
}
return $r;
}
/**
* @param array<int, object> $nodes
* @param array<int|string, array<int, object>> $childrenHashmap
*
* @return void
*/
protected function populateChildrenArray($nodes, $childrenHashmap)
{
foreach ($nodes as $node) {
$nodeId = $this->getPropertyValue($node, $this->idField);
$childrenCollection = $this->getPropertyValue($node, $this->childrenField);
if (null === $childrenCollection) {
$childrenCollection = new ArrayCollection();
$this->setPropertyValue($node, $this->childrenField, $childrenCollection);
}
// Initialize all the children collections in order to avoid "SELECT" queries.
if ($childrenCollection instanceof PersistentCollection && !$childrenCollection->isInitialized()) {
$childrenCollection->setInitialized(true);
}
if (!isset($childrenHashmap[$nodeId])) {
continue;
}
$childrenCollection->clear();
foreach ($childrenHashmap[$nodeId] as $child) {
$childrenCollection->add($child);
}
}
}
/**
* @param array<int, object> $nodes
*
* @return array<int, object>
*/
protected function getRootNodes($nodes)
{
$idHashmap = $this->buildIdHashmap($nodes);
$rootNodes = [];
foreach ($nodes as $node) {
$parentProxy = $this->getPropertyValue($node, $this->config['parent']);
$parentId = self::NO_PARENT_ID;
if (null !== $parentProxy) {
$parentId = $this->getPropertyValue($parentProxy, $this->idField);
}
if (self::NO_PARENT_ID === $parentId || !array_key_exists($parentId, $idHashmap)) {
$rootNodes[] = $node;
}
}
return $rootNodes;
}
/**
* Creates a hashmap of all nodes returned in the query
*
* ```
* [node1.id => true, node2.id => true, ...]
* ```
*
* @param array<int, object> $nodes
*
* @return array<mixed, true>
*/
protected function buildIdHashmap(array $nodes)
{
$ids = [];
foreach ($nodes as $node) {
$id = $this->getPropertyValue($node, $this->idField);
$ids[$id] = true;
}
return $ids;
}
/**
* @param string $entityClass
*
* @phpstan-param class-string $entityClass
*
* @return string
*/
protected function getIdField($entityClass)
{
$meta = $this->getClassMetadata($entityClass);
return $meta->getSingleIdentifierFieldName();
}
/**
* @return string
*/
protected function getParentField()
{
if (!isset($this->config['parent'])) {
throw new InvalidMappingException('The `parent` property is required for the TreeHydrator to work');
}
return $this->config['parent'];
}
/**
* @param string $entityClass
*
* @phpstan-param class-string $entityClass
*
* @return string
*/
protected function getChildrenField($entityClass)
{
$meta = $this->getClassMetadata($entityClass);
foreach ($meta->getReflectionProperties() as $property) {
// Skip properties that have no association
if (!$meta->hasAssociation($property->getName())) {
continue;
}
$associationMapping = $meta->getAssociationMapping($property->getName());
if ($associationMapping instanceof OneToManyAssociationMapping) {
if ($associationMapping->mappedBy !== $this->parentField) {
continue;
}
return $associationMapping->fieldName;
}
if (!isset($associationMapping['mappedBy'])) {
continue;
}
// Make sure the association is mapped by the parent property
if ($associationMapping['mappedBy'] !== $this->parentField) {
continue;
}
return $associationMapping['fieldName'];
}
throw new InvalidMappingException('The children property could not found. It is identified through the `mappedBy` annotation to your parent property.');
}
/**
* @return TreeListener
*/
protected function getTreeListener(EntityManagerInterface $em)
{
foreach ($em->getEventManager()->getAllListeners() as $listeners) {
foreach ($listeners as $listener) {
if ($listener instanceof TreeListener) {
return $listener;
}
}
}
throw new InvalidMappingException('Tree listener was not found on your entity manager, it must be hooked into the event manager');
}
/**
* @param array<int, object> $data
*
* @return string
*/
protected function getEntityClassFromHydratedData($data)
{
$firstMappedEntity = array_values($data);
$firstMappedEntity = $firstMappedEntity[0];
return $this->getEntityManager()->getClassMetadata(get_class($firstMappedEntity))->rootEntityName;
}
/**
* @param object $object
* @param string $property
*
* @return mixed
*/
protected function getPropertyValue($object, $property)
{
$meta = $this->getEntityManager()->getClassMetadata(get_class($object));
return $meta->getFieldValue($object, $property);
}
}