/
PersistenceBuilder.php
464 lines (401 loc) · 19.5 KB
/
PersistenceBuilder.php
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
<?php
declare(strict_types=1);
namespace Doctrine\ODM\MongoDB\Persisters;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ODM\MongoDB\PersistentCollection\PersistentCollectionInterface;
use Doctrine\ODM\MongoDB\Types\Type;
use Doctrine\ODM\MongoDB\UnitOfWork;
use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
use function array_search;
use function array_values;
use function get_class;
/**
* PersistenceBuilder builds the queries used by the persisters to update and insert
* documents when a DocumentManager is flushed. It uses the changeset information in the
* UnitOfWork to build queries using atomic operators like $set, $unset, etc.
*
*/
class PersistenceBuilder
{
/**
* The DocumentManager instance.
*
* @var DocumentManager
*/
private $dm;
/**
* The UnitOfWork instance.
*
* @var UnitOfWork
*/
private $uow;
/**
* Initializes a new PersistenceBuilder instance.
*
*/
public function __construct(DocumentManager $dm, UnitOfWork $uow)
{
$this->dm = $dm;
$this->uow = $uow;
}
/**
* Prepares the array that is ready to be inserted to mongodb for a given object document.
*
* @param object $document
* @return array $insertData
*/
public function prepareInsertData($document)
{
$class = $this->dm->getClassMetadata(get_class($document));
$changeset = $this->uow->getDocumentChangeSet($document);
$insertData = [];
foreach ($class->fieldMappings as $mapping) {
$new = $changeset[$mapping['fieldName']][1] ?? null;
if ($new === null && $mapping['nullable']) {
$insertData[$mapping['name']] = null;
}
/* Nothing more to do for null values, since we're either storing
* them (if nullable was true) or not.
*/
if ($new === null) {
continue;
}
// @Field, @String, @Date, etc.
if (! isset($mapping['association'])) {
$insertData[$mapping['name']] = Type::getType($mapping['type'])->convertToDatabaseValue($new);
// @ReferenceOne
} elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::REFERENCE_ONE) {
$insertData[$mapping['name']] = $this->prepareReferencedDocumentValue($mapping, $new);
// @EmbedOne
} elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::EMBED_ONE) {
$insertData[$mapping['name']] = $this->prepareEmbeddedDocumentValue($mapping, $new);
// @ReferenceMany, @EmbedMany
// We're excluding collections using addToSet since there is a risk
// of duplicated entries stored in the collection
} elseif ($mapping['type'] === ClassMetadata::MANY && ! $mapping['isInverseSide']
&& $mapping['strategy'] !== ClassMetadata::STORAGE_STRATEGY_ADD_TO_SET && ! $new->isEmpty()) {
$insertData[$mapping['name']] = $this->prepareAssociatedCollectionValue($new, true);
}
}
// add discriminator if the class has one
if (isset($class->discriminatorField)) {
$insertData[$class->discriminatorField] = $class->discriminatorValue ?? $class->name;
}
return $insertData;
}
/**
* Prepares the update query to update a given document object in mongodb.
*
* @param object $document
* @return array $updateData
*/
public function prepareUpdateData($document)
{
$class = $this->dm->getClassMetadata(get_class($document));
$changeset = $this->uow->getDocumentChangeSet($document);
$updateData = [];
foreach ($changeset as $fieldName => $change) {
$mapping = $class->fieldMappings[$fieldName];
// skip non embedded document identifiers
if (! $class->isEmbeddedDocument && ! empty($mapping['id'])) {
continue;
}
list($old, $new) = $change;
// Scalar fields
if (! isset($mapping['association'])) {
if ($new === null && $mapping['nullable'] !== true) {
$updateData['$unset'][$mapping['name']] = true;
} else {
if ($new !== null && isset($mapping['strategy']) && $mapping['strategy'] === ClassMetadata::STORAGE_STRATEGY_INCREMENT) {
$operator = '$inc';
$value = Type::getType($mapping['type'])->convertToDatabaseValue($new - $old);
} else {
$operator = '$set';
$value = $new === null ? null : Type::getType($mapping['type'])->convertToDatabaseValue($new);
}
$updateData[$operator][$mapping['name']] = $value;
}
// @EmbedOne
} elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::EMBED_ONE) {
// If we have a new embedded document then lets set the whole thing
if ($new && $this->uow->isScheduledForInsert($new)) {
$updateData['$set'][$mapping['name']] = $this->prepareEmbeddedDocumentValue($mapping, $new);
// If we don't have a new value then lets unset the embedded document
} elseif (! $new) {
$updateData['$unset'][$mapping['name']] = true;
// Update existing embedded document
} else {
$update = $this->prepareUpdateData($new);
foreach ($update as $cmd => $values) {
foreach ($values as $key => $value) {
$updateData[$cmd][$mapping['name'] . '.' . $key] = $value;
}
}
}
// @ReferenceMany, @EmbedMany
} elseif (isset($mapping['association']) && $mapping['type'] === 'many' && $new) {
if (CollectionHelper::isAtomic($mapping['strategy']) && $this->uow->isCollectionScheduledForUpdate($new)) {
$updateData['$set'][$mapping['name']] = $this->prepareAssociatedCollectionValue($new, true);
} elseif (CollectionHelper::isAtomic($mapping['strategy']) && $this->uow->isCollectionScheduledForDeletion($new)) {
$updateData['$unset'][$mapping['name']] = true;
$this->uow->unscheduleCollectionDeletion($new);
} elseif (CollectionHelper::isAtomic($mapping['strategy']) && $this->uow->isCollectionScheduledForDeletion($old)) {
$updateData['$unset'][$mapping['name']] = true;
$this->uow->unscheduleCollectionDeletion($old);
} elseif ($mapping['association'] === ClassMetadata::EMBED_MANY) {
foreach ($new as $key => $embeddedDoc) {
if ($this->uow->isScheduledForInsert($embeddedDoc)) {
continue;
}
$update = $this->prepareUpdateData($embeddedDoc);
foreach ($update as $cmd => $values) {
foreach ($values as $name => $value) {
$updateData[$cmd][$mapping['name'] . '.' . $key . '.' . $name] = $value;
}
}
}
}
// @ReferenceOne
} elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::REFERENCE_ONE) {
if (isset($new) || $mapping['nullable'] === true) {
$updateData['$set'][$mapping['name']] = $new === null ? null : $this->prepareReferencedDocumentValue($mapping, $new);
} else {
$updateData['$unset'][$mapping['name']] = true;
}
}
}
// collections that aren't dirty but could be subject to update are
// excluded from change set, let's go through them now
foreach ($this->uow->getScheduledCollections($document) as $coll) {
$mapping = $coll->getMapping();
if (CollectionHelper::isAtomic($mapping['strategy']) && $this->uow->isCollectionScheduledForUpdate($coll)) {
$updateData['$set'][$mapping['name']] = $this->prepareAssociatedCollectionValue($coll, true);
} elseif (CollectionHelper::isAtomic($mapping['strategy']) && $this->uow->isCollectionScheduledForDeletion($coll)) {
$updateData['$unset'][$mapping['name']] = true;
$this->uow->unscheduleCollectionDeletion($coll);
}
// @ReferenceMany is handled by CollectionPersister
}
return $updateData;
}
/**
* Prepares the update query to upsert a given document object in mongodb.
*
* @param object $document
* @return array $updateData
*/
public function prepareUpsertData($document)
{
$class = $this->dm->getClassMetadata(get_class($document));
$changeset = $this->uow->getDocumentChangeSet($document);
$updateData = [];
foreach ($changeset as $fieldName => $change) {
$mapping = $class->fieldMappings[$fieldName];
list($old, $new) = $change;
// Scalar fields
if (! isset($mapping['association'])) {
if ($new !== null) {
if (empty($mapping['id']) && isset($mapping['strategy']) && $mapping['strategy'] === ClassMetadata::STORAGE_STRATEGY_INCREMENT) {
$operator = '$inc';
$value = Type::getType($mapping['type'])->convertToDatabaseValue($new - $old);
} else {
$operator = '$set';
$value = Type::getType($mapping['type'])->convertToDatabaseValue($new);
}
$updateData[$operator][$mapping['name']] = $value;
} elseif ($mapping['nullable'] === true) {
$updateData['$setOnInsert'][$mapping['name']] = null;
}
// @EmbedOne
} elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::EMBED_ONE) {
// If we don't have a new value then do nothing on upsert
// If we have a new embedded document then lets set the whole thing
if ($new && $this->uow->isScheduledForInsert($new)) {
$updateData['$set'][$mapping['name']] = $this->prepareEmbeddedDocumentValue($mapping, $new);
} elseif ($new) {
// Update existing embedded document
$update = $this->prepareUpsertData($new);
foreach ($update as $cmd => $values) {
foreach ($values as $key => $value) {
$updateData[$cmd][$mapping['name'] . '.' . $key] = $value;
}
}
}
// @ReferenceOne
} elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::REFERENCE_ONE) {
if (isset($new) || $mapping['nullable'] === true) {
$updateData['$set'][$mapping['name']] = $new === null ? null : $this->prepareReferencedDocumentValue($mapping, $new);
}
// @ReferenceMany, @EmbedMany
} elseif ($mapping['type'] === ClassMetadata::MANY && ! $mapping['isInverseSide']
&& $new instanceof PersistentCollectionInterface && $new->isDirty()
&& CollectionHelper::isAtomic($mapping['strategy'])) {
$updateData['$set'][$mapping['name']] = $this->prepareAssociatedCollectionValue($new, true);
}
// @EmbedMany and @ReferenceMany are handled by CollectionPersister
}
// add discriminator if the class has one
if (isset($class->discriminatorField)) {
$updateData['$set'][$class->discriminatorField] = $class->discriminatorValue ?? $class->name;
}
return $updateData;
}
/**
* Returns the reference representation to be stored in MongoDB.
*
* If the document does not have an identifier and the mapping calls for a
* simple reference, null may be returned.
*
* @param array $referenceMapping
* @param object $document
* @return array|null
*/
public function prepareReferencedDocumentValue(array $referenceMapping, $document)
{
return $this->dm->createReference($document, $referenceMapping);
}
/**
* Returns the embedded document to be stored in MongoDB.
*
* The return value will usually be an associative array with string keys
* corresponding to field names on the embedded document. An object may be
* returned if the document is empty, to ensure that a BSON object will be
* stored in lieu of an array.
*
* If $includeNestedCollections is true, nested collections will be included
* in this prepared value and the option will cascade to all embedded
* associations. If any nested PersistentCollections (embed or reference)
* within this value were previously scheduled for deletion or update, they
* will also be unscheduled.
*
* @param array $embeddedMapping
* @param object $embeddedDocument
* @param bool $includeNestedCollections
* @return array|object
* @throws \UnexpectedValueException If an unsupported associating mapping is found.
*/
public function prepareEmbeddedDocumentValue(array $embeddedMapping, $embeddedDocument, $includeNestedCollections = false)
{
$embeddedDocumentValue = [];
$class = $this->dm->getClassMetadata(get_class($embeddedDocument));
foreach ($class->fieldMappings as $mapping) {
// Skip notSaved fields
if (! empty($mapping['notSaved'])) {
continue;
}
// Inline ClassMetadata::getFieldValue()
$rawValue = $class->reflFields[$mapping['fieldName']]->getValue($embeddedDocument);
$value = null;
if ($rawValue !== null) {
switch ($mapping['association'] ?? null) {
// @Field, @String, @Date, etc.
case null:
$value = Type::getType($mapping['type'])->convertToDatabaseValue($rawValue);
break;
case ClassMetadata::EMBED_ONE:
case ClassMetadata::REFERENCE_ONE:
// Nested collections should only be included for embedded relationships
$value = $this->prepareAssociatedDocumentValue($mapping, $rawValue, $includeNestedCollections && isset($mapping['embedded']));
break;
case ClassMetadata::EMBED_MANY:
case ClassMetadata::REFERENCE_MANY:
// Skip PersistentCollections already scheduled for deletion
if (! $includeNestedCollections && $rawValue instanceof PersistentCollectionInterface
&& $this->uow->isCollectionScheduledForDeletion($rawValue)) {
break;
}
$value = $this->prepareAssociatedCollectionValue($rawValue, $includeNestedCollections);
break;
default:
throw new \UnexpectedValueException('Unsupported mapping association: ' . $mapping['association']);
}
}
// Omit non-nullable fields that would have a null value
if ($value === null && $mapping['nullable'] === false) {
continue;
}
$embeddedDocumentValue[$mapping['name']] = $value;
}
/* Add a discriminator value if the embedded document is not mapped
* explicitly to a targetDocument class.
*/
if (! isset($embeddedMapping['targetDocument'])) {
$discriminatorField = $embeddedMapping['discriminatorField'];
$discriminatorValue = isset($embeddedMapping['discriminatorMap'])
? array_search($class->name, $embeddedMapping['discriminatorMap'])
: $class->name;
/* If the discriminator value was not found in the map, use the full
* class name. In the future, it may be preferable to throw an
* exception here (perhaps based on some strictness option).
*
* @see DocumentManager::createDBRef()
*/
if ($discriminatorValue === false) {
$discriminatorValue = $class->name;
}
$embeddedDocumentValue[$discriminatorField] = $discriminatorValue;
}
/* If the class has a discriminator (field and value), use it. A child
* class that is not defined in the discriminator map may only have a
* discriminator field and no value, so default to the full class name.
*/
if (isset($class->discriminatorField)) {
$embeddedDocumentValue[$class->discriminatorField] = $class->discriminatorValue ?? $class->name;
}
// Ensure empty embedded documents are stored as BSON objects
if (empty($embeddedDocumentValue)) {
return (object) $embeddedDocumentValue;
}
/* @todo Consider always casting the return value to an object, or
* building $embeddedDocumentValue as an object instead of an array, to
* handle the edge case where all database field names are sequential,
* numeric keys.
*/
return $embeddedDocumentValue;
}
/**
* Returns the embedded document or reference representation to be stored.
*
* @param array $mapping
* @param object $document
* @param bool $includeNestedCollections
* @return array|object|null
* @throws \InvalidArgumentException If the mapping is neither embedded nor reference.
*/
public function prepareAssociatedDocumentValue(array $mapping, $document, $includeNestedCollections = false)
{
if (isset($mapping['embedded'])) {
return $this->prepareEmbeddedDocumentValue($mapping, $document, $includeNestedCollections);
}
if (isset($mapping['reference'])) {
return $this->prepareReferencedDocumentValue($mapping, $document);
}
throw new \InvalidArgumentException('Mapping is neither embedded nor reference.');
}
/**
* Returns the collection representation to be stored and unschedules it afterwards.
*
* @param bool $includeNestedCollections
* @return array
*/
public function prepareAssociatedCollectionValue(PersistentCollectionInterface $coll, $includeNestedCollections = false)
{
$mapping = $coll->getMapping();
$pb = $this;
$callback = isset($mapping['embedded'])
? function ($v) use ($pb, $mapping, $includeNestedCollections) {
return $pb->prepareEmbeddedDocumentValue($mapping, $v, $includeNestedCollections);
}
: function ($v) use ($pb, $mapping) {
return $pb->prepareReferencedDocumentValue($mapping, $v);
};
$setData = $coll->map($callback)->toArray();
if (CollectionHelper::isList($mapping['strategy'])) {
$setData = array_values($setData);
}
$this->uow->unscheduleCollectionDeletion($coll);
$this->uow->unscheduleCollectionUpdate($coll);
return $setData;
}
}