forked from doctrine/mongodb-odm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDocumentPersister.php
1563 lines (1295 loc) · 55.1 KB
/
DocumentPersister.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace Doctrine\ODM\MongoDB\Persisters;
use BadMethodCallException;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Hydrator\HydratorException;
use Doctrine\ODM\MongoDB\Hydrator\HydratorFactory;
use Doctrine\ODM\MongoDB\Iterator\CachingIterator;
use Doctrine\ODM\MongoDB\Iterator\HydratingIterator;
use Doctrine\ODM\MongoDB\Iterator\Iterator;
use Doctrine\ODM\MongoDB\Iterator\PrimingIterator;
use Doctrine\ODM\MongoDB\LockException;
use Doctrine\ODM\MongoDB\LockMode;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ODM\MongoDB\MongoDBException;
use Doctrine\ODM\MongoDB\PersistentCollection\PersistentCollectionException;
use Doctrine\ODM\MongoDB\PersistentCollection\PersistentCollectionInterface;
use Doctrine\ODM\MongoDB\Query\CriteriaMerger;
use Doctrine\ODM\MongoDB\Query\Query;
use Doctrine\ODM\MongoDB\Query\ReferencePrimer;
use Doctrine\ODM\MongoDB\Types\Type;
use Doctrine\ODM\MongoDB\Types\Versionable;
use Doctrine\ODM\MongoDB\UnitOfWork;
use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
use Doctrine\Persistence\Mapping\MappingException;
use InvalidArgumentException;
use MongoDB\BSON\ObjectId;
use MongoDB\Collection;
use MongoDB\Driver\Cursor;
use MongoDB\Driver\Exception\Exception as DriverException;
use MongoDB\Driver\Exception\WriteException;
use MongoDB\Driver\WriteConcern;
use MongoDB\GridFS\Bucket;
use ProxyManager\Proxy\GhostObjectInterface;
use stdClass;
use function array_combine;
use function array_fill;
use function array_intersect_key;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function array_search;
use function array_slice;
use function array_values;
use function assert;
use function count;
use function explode;
use function get_class;
use function get_object_vars;
use function gettype;
use function implode;
use function in_array;
use function is_array;
use function is_object;
use function is_scalar;
use function is_string;
use function spl_object_hash;
use function sprintf;
use function strpos;
use function strtolower;
use function trigger_deprecation;
/**
* The DocumentPersister is responsible for persisting documents.
*
* @internal
*/
final class DocumentPersister
{
/** @var PersistenceBuilder */
private $pb;
/** @var DocumentManager */
private $dm;
/** @var UnitOfWork */
private $uow;
/** @var ClassMetadata */
private $class;
/** @var Collection|null */
private $collection;
/** @var Bucket|null */
private $bucket;
/**
* Array of queued inserts for the persister to insert.
*
* @var array
*/
private $queuedInserts = [];
/**
* Array of queued inserts for the persister to insert.
*
* @var array
*/
private $queuedUpserts = [];
/** @var CriteriaMerger */
private $cm;
/** @var CollectionPersister */
private $cp;
/** @var HydratorFactory */
private $hydratorFactory;
public function __construct(
PersistenceBuilder $pb,
DocumentManager $dm,
UnitOfWork $uow,
HydratorFactory $hydratorFactory,
ClassMetadata $class,
?CriteriaMerger $cm = null
) {
$this->pb = $pb;
$this->dm = $dm;
$this->cm = $cm ?: new CriteriaMerger();
$this->uow = $uow;
$this->hydratorFactory = $hydratorFactory;
$this->class = $class;
$this->cp = $this->uow->getCollectionPersister();
if ($class->isEmbeddedDocument || $class->isQueryResultDocument) {
return;
}
$this->collection = $dm->getDocumentCollection($class->name);
if (! $class->isFile) {
return;
}
$this->bucket = $dm->getDocumentBucket($class->name);
}
public function getInserts(): array
{
return $this->queuedInserts;
}
public function isQueuedForInsert(object $document): bool
{
return isset($this->queuedInserts[spl_object_hash($document)]);
}
/**
* Adds a document to the queued insertions.
* The document remains queued until {@link executeInserts} is invoked.
*/
public function addInsert(object $document): void
{
$this->queuedInserts[spl_object_hash($document)] = $document;
}
public function getUpserts(): array
{
return $this->queuedUpserts;
}
public function isQueuedForUpsert(object $document): bool
{
return isset($this->queuedUpserts[spl_object_hash($document)]);
}
/**
* Adds a document to the queued upserts.
* The document remains queued until {@link executeUpserts} is invoked.
*/
public function addUpsert(object $document): void
{
$this->queuedUpserts[spl_object_hash($document)] = $document;
}
/**
* Gets the ClassMetadata instance of the document class this persister is
* used for.
*/
public function getClassMetadata(): ClassMetadata
{
return $this->class;
}
/**
* Executes all queued document insertions.
*
* Queued documents without an ID will inserted in a batch and queued
* documents with an ID will be upserted individually.
*
* If no inserts are queued, invoking this method is a NOOP.
*
* @throws DriverException
*/
public function executeInserts(array $options = []): void
{
if (! $this->queuedInserts) {
return;
}
$inserts = [];
$options = $this->getWriteOptions($options);
foreach ($this->queuedInserts as $oid => $document) {
$data = $this->pb->prepareInsertData($document);
// Set the initial version for each insert
if ($this->class->isVersioned) {
$versionMapping = $this->class->fieldMappings[$this->class->versionField];
$nextVersion = $this->class->reflFields[$this->class->versionField]->getValue($document);
$type = Type::getType($versionMapping['type']);
assert($type instanceof Versionable);
if ($nextVersion === null) {
$nextVersion = $type->getNextVersion(null);
$this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion);
}
$data[$versionMapping['name']] = $type->convertPHPToDatabaseValue($nextVersion);
}
$inserts[] = $data;
}
try {
assert($this->collection instanceof Collection);
$this->collection->insertMany($inserts, $options);
} catch (DriverException $e) {
$this->queuedInserts = [];
throw $e;
}
/* All collections except for ones using addToSet have already been
* saved. We have left these to be handled separately to avoid checking
* collection for uniqueness on PHP side.
*/
foreach ($this->queuedInserts as $document) {
$this->handleCollections($document, $options);
}
$this->queuedInserts = [];
}
/**
* Executes all queued document upserts.
*
* Queued documents with an ID are upserted individually.
*
* If no upserts are queued, invoking this method is a NOOP.
*/
public function executeUpserts(array $options = []): void
{
if (! $this->queuedUpserts) {
return;
}
$options = $this->getWriteOptions($options);
foreach ($this->queuedUpserts as $oid => $document) {
try {
$this->executeUpsert($document, $options);
$this->handleCollections($document, $options);
unset($this->queuedUpserts[$oid]);
} catch (WriteException $e) {
unset($this->queuedUpserts[$oid]);
throw $e;
}
}
}
/**
* Executes a single upsert in {@link executeUpserts}
*/
private function executeUpsert(object $document, array $options): void
{
$options['upsert'] = true;
$criteria = $this->getQueryForDocument($document);
$data = $this->pb->prepareUpsertData($document);
// Set the initial version for each upsert
if ($this->class->isVersioned) {
$versionMapping = $this->class->fieldMappings[$this->class->versionField];
$nextVersion = $this->class->reflFields[$this->class->versionField]->getValue($document);
$type = Type::getType($versionMapping['type']);
assert($type instanceof Versionable);
if ($nextVersion === null) {
$nextVersion = $type->getNextVersion(null);
$this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion);
}
$data['$set'][$versionMapping['name']] = $type->convertPHPToDatabaseValue($nextVersion);
}
foreach (array_keys($criteria) as $field) {
unset($data['$set'][$field]);
unset($data['$inc'][$field]);
unset($data['$setOnInsert'][$field]);
}
// Do not send empty update operators
foreach (['$set', '$inc', '$setOnInsert'] as $operator) {
if (! empty($data[$operator])) {
continue;
}
unset($data[$operator]);
}
/* If there are no modifiers remaining, we're upserting a document with
* an identifier as its only field. Since a document with the identifier
* may already exist, the desired behavior is "insert if not exists" and
* NOOP otherwise. MongoDB 2.6+ does not allow empty modifiers, so $set
* the identifier to the same value in our criteria.
*
* This will fail for versions before MongoDB 2.6, which require an
* empty $set modifier. The best we can do (without attempting to check
* server versions in advance) is attempt the 2.6+ behavior and retry
* after the relevant exception.
*
* See: https://jira.mongodb.org/browse/SERVER-12266
*/
if (empty($data)) {
$retry = true;
$data = ['$set' => ['_id' => $criteria['_id']]];
}
try {
assert($this->collection instanceof Collection);
$this->collection->updateOne($criteria, $data, $options);
return;
} catch (WriteException $e) {
if (empty($retry) || strpos($e->getMessage(), 'Mod on _id not allowed') === false) {
throw $e;
}
}
assert($this->collection instanceof Collection);
$this->collection->updateOne($criteria, ['$set' => new stdClass()], $options);
}
/**
* Updates the already persisted document if it has any new changesets.
*
* @throws LockException
*/
public function update(object $document, array $options = []): void
{
$update = $this->pb->prepareUpdateData($document);
$query = $this->getQueryForDocument($document);
foreach (array_keys($query) as $field) {
unset($update['$set'][$field]);
}
if (empty($update['$set'])) {
unset($update['$set']);
}
// Include versioning logic to set the new version value in the database
// and to ensure the version has not changed since this document object instance
// was fetched from the database
$nextVersion = null;
if ($this->class->isVersioned) {
$versionMapping = $this->class->fieldMappings[$this->class->versionField];
$currentVersion = $this->class->reflFields[$this->class->versionField]->getValue($document);
$type = Type::getType($versionMapping['type']);
assert($type instanceof Versionable);
$nextVersion = $type->getNextVersion($currentVersion);
$update['$set'][$versionMapping['name']] = Type::convertPHPToDatabaseValue($nextVersion);
$query[$versionMapping['name']] = Type::convertPHPToDatabaseValue($currentVersion);
}
if (! empty($update)) {
// Include locking logic so that if the document object in memory is currently
// locked then it will remove it, otherwise it ensures the document is not locked.
if ($this->class->isLockable) {
$isLocked = $this->class->reflFields[$this->class->lockField]->getValue($document);
$lockMapping = $this->class->fieldMappings[$this->class->lockField];
if ($isLocked) {
$update['$unset'] = [$lockMapping['name'] => true];
} else {
$query[$lockMapping['name']] = ['$exists' => false];
}
}
$options = $this->getWriteOptions($options);
assert($this->collection instanceof Collection);
$result = $this->collection->updateOne($query, $update, $options);
if (($this->class->isVersioned || $this->class->isLockable) && $result->getModifiedCount() !== 1) {
throw LockException::lockFailed($document);
}
if ($this->class->isVersioned) {
$this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion);
}
}
$this->handleCollections($document, $options);
}
/**
* Removes document from mongo
*
* @throws LockException
*/
public function delete(object $document, array $options = []): void
{
if ($this->bucket instanceof Bucket) {
$documentIdentifier = $this->uow->getDocumentIdentifier($document);
$databaseIdentifier = $this->class->getDatabaseIdentifierValue($documentIdentifier);
$this->bucket->delete($databaseIdentifier);
return;
}
$query = $this->getQueryForDocument($document);
if ($this->class->isLockable) {
$query[$this->class->lockField] = ['$exists' => false];
}
$options = $this->getWriteOptions($options);
assert($this->collection instanceof Collection);
$result = $this->collection->deleteOne($query, $options);
if (($this->class->isVersioned || $this->class->isLockable) && ! $result->getDeletedCount()) {
throw LockException::lockFailed($document);
}
}
/**
* Refreshes a managed document.
*/
public function refresh(object $document): void
{
assert($this->collection instanceof Collection);
$query = $this->getQueryForDocument($document);
$data = $this->collection->findOne($query);
if ($data === null) {
throw MongoDBException::cannotRefreshDocument();
}
$data = $this->hydratorFactory->hydrate($document, (array) $data);
$this->uow->setOriginalDocumentData($document, $data);
}
/**
* Finds a document by a set of criteria.
*
* If a scalar or MongoDB\BSON\ObjectId is provided for $criteria, it will
* be used to match an _id value.
*
* @param mixed $criteria Query criteria
*
* @throws LockException
*
* @todo Check identity map? loadById method? Try to guess whether
* $criteria is the id?
*/
public function load($criteria, ?object $document = null, array $hints = [], int $lockMode = 0, ?array $sort = null): ?object
{
// TODO: remove this
if ($criteria === null || is_scalar($criteria) || $criteria instanceof ObjectId) {
$criteria = ['_id' => $criteria];
}
$criteria = $this->prepareQueryOrNewObj($criteria);
$criteria = $this->addDiscriminatorToPreparedQuery($criteria);
$criteria = $this->addFilterToPreparedQuery($criteria);
$options = [];
if ($sort !== null) {
$options['sort'] = $this->prepareSort($sort);
}
assert($this->collection instanceof Collection);
$result = $this->collection->findOne($criteria, $options);
$result = $result !== null ? (array) $result : null;
if ($this->class->isLockable) {
$lockMapping = $this->class->fieldMappings[$this->class->lockField];
if (isset($result[$lockMapping['name']]) && $result[$lockMapping['name']] === LockMode::PESSIMISTIC_WRITE) {
throw LockException::lockFailed($document);
}
}
if ($result === null) {
return null;
}
return $this->createDocument($result, $document, $hints);
}
/**
* Finds documents by a set of criteria.
*/
public function loadAll(array $criteria = [], ?array $sort = null, ?int $limit = null, ?int $skip = null): Iterator
{
$criteria = $this->prepareQueryOrNewObj($criteria);
$criteria = $this->addDiscriminatorToPreparedQuery($criteria);
$criteria = $this->addFilterToPreparedQuery($criteria);
$options = [];
if ($sort !== null) {
$options['sort'] = $this->prepareSort($sort);
}
if ($limit !== null) {
$options['limit'] = $limit;
}
if ($skip !== null) {
$options['skip'] = $skip;
}
assert($this->collection instanceof Collection);
$baseCursor = $this->collection->find($criteria, $options);
return $this->wrapCursor($baseCursor);
}
/**
* @throws MongoDBException
*/
private function getShardKeyQuery(object $document): array
{
if (! $this->class->isSharded()) {
return [];
}
$shardKey = $this->class->getShardKey();
$keys = array_keys($shardKey['keys']);
$data = $this->uow->getDocumentActualData($document);
$shardKeyQueryPart = [];
foreach ($keys as $key) {
assert(is_string($key));
$mapping = $this->class->getFieldMappingByDbFieldName($key);
$this->guardMissingShardKey($document, $key, $data);
if (isset($mapping['association']) && $mapping['association'] === ClassMetadata::REFERENCE_ONE) {
$reference = $this->prepareReference(
$key,
$data[$mapping['fieldName']],
$mapping,
false
);
foreach ($reference as $keyValue) {
$shardKeyQueryPart[$keyValue[0]] = $keyValue[1];
}
} else {
$value = Type::getType($mapping['type'])->convertToDatabaseValue($data[$mapping['fieldName']]);
$shardKeyQueryPart[$key] = $value;
}
}
return $shardKeyQueryPart;
}
/**
* Wraps the supplied base cursor in the corresponding ODM class.
*/
private function wrapCursor(Cursor $baseCursor): Iterator
{
return new CachingIterator(new HydratingIterator($baseCursor, $this->dm->getUnitOfWork(), $this->class));
}
/**
* Checks whether the given managed document exists in the database.
*/
public function exists(object $document): bool
{
$id = $this->class->getIdentifierObject($document);
assert($this->collection instanceof Collection);
return (bool) $this->collection->findOne(['_id' => $id], ['_id']);
}
/**
* Locks document by storing the lock mode on the mapped lock field.
*/
public function lock(object $document, int $lockMode): void
{
$id = $this->uow->getDocumentIdentifier($document);
$criteria = ['_id' => $this->class->getDatabaseIdentifierValue($id)];
$lockMapping = $this->class->fieldMappings[$this->class->lockField];
assert($this->collection instanceof Collection);
$this->collection->updateOne($criteria, ['$set' => [$lockMapping['name'] => $lockMode]]);
$this->class->reflFields[$this->class->lockField]->setValue($document, $lockMode);
}
/**
* Releases any lock that exists on this document.
*/
public function unlock(object $document): void
{
$id = $this->uow->getDocumentIdentifier($document);
$criteria = ['_id' => $this->class->getDatabaseIdentifierValue($id)];
$lockMapping = $this->class->fieldMappings[$this->class->lockField];
assert($this->collection instanceof Collection);
$this->collection->updateOne($criteria, ['$unset' => [$lockMapping['name'] => true]]);
$this->class->reflFields[$this->class->lockField]->setValue($document, null);
}
/**
* Creates or fills a single document object from an query result.
*
* @param array $result The query result.
* @param object $document The document object to fill, if any.
* @param array $hints Hints for document creation.
*
* @return object The filled and managed document object.
*/
private function createDocument(array $result, ?object $document = null, array $hints = []): object
{
if ($document !== null) {
$hints[Query::HINT_REFRESH] = true;
$id = $this->class->getPHPIdentifierValue($result['_id']);
$this->uow->registerManaged($document, $id, $result);
}
return $this->uow->getOrCreateDocument($this->class->name, $result, $hints, $document);
}
/**
* Loads a PersistentCollection data. Used in the initialize() method.
*/
public function loadCollection(PersistentCollectionInterface $collection): void
{
$mapping = $collection->getMapping();
switch ($mapping['association']) {
case ClassMetadata::EMBED_MANY:
$this->loadEmbedManyCollection($collection);
break;
case ClassMetadata::REFERENCE_MANY:
if (isset($mapping['repositoryMethod']) && $mapping['repositoryMethod']) {
$this->loadReferenceManyWithRepositoryMethod($collection);
} else {
if ($mapping['isOwningSide']) {
$this->loadReferenceManyCollectionOwningSide($collection);
} else {
$this->loadReferenceManyCollectionInverseSide($collection);
}
}
break;
}
}
private function loadEmbedManyCollection(PersistentCollectionInterface $collection): void
{
$embeddedDocuments = $collection->getMongoData();
$mapping = $collection->getMapping();
$owner = $collection->getOwner();
if (! $embeddedDocuments) {
return;
}
if ($owner === null) {
throw PersistentCollectionException::ownerRequiredToLoadCollection();
}
foreach ($embeddedDocuments as $key => $embeddedDocument) {
$className = $this->uow->getClassNameForAssociation($mapping, $embeddedDocument);
$embeddedMetadata = $this->dm->getClassMetadata($className);
$embeddedDocumentObject = $embeddedMetadata->newInstance();
if (! is_array($embeddedDocument)) {
throw HydratorException::associationItemTypeMismatch(get_class($owner), $mapping['name'], $key, 'array', gettype($embeddedDocument));
}
$this->uow->setParentAssociation($embeddedDocumentObject, $mapping, $owner, $mapping['name'] . '.' . $key);
$data = $this->hydratorFactory->hydrate($embeddedDocumentObject, $embeddedDocument, $collection->getHints());
$id = $data[$embeddedMetadata->identifier] ?? null;
if (empty($collection->getHints()[Query::HINT_READ_ONLY])) {
$this->uow->registerManaged($embeddedDocumentObject, $id, $data);
}
if (CollectionHelper::isHash($mapping['strategy'])) {
$collection->set($key, $embeddedDocumentObject);
} else {
$collection->add($embeddedDocumentObject);
}
}
}
private function loadReferenceManyCollectionOwningSide(PersistentCollectionInterface $collection): void
{
$hints = $collection->getHints();
$mapping = $collection->getMapping();
$owner = $collection->getOwner();
$groupedIds = [];
if ($owner === null) {
throw PersistentCollectionException::ownerRequiredToLoadCollection();
}
$sorted = isset($mapping['sort']) && $mapping['sort'];
foreach ($collection->getMongoData() as $key => $reference) {
$className = $this->uow->getClassNameForAssociation($mapping, $reference);
if ($mapping['storeAs'] !== ClassMetadata::REFERENCE_STORE_AS_ID && ! is_array($reference)) {
throw HydratorException::associationItemTypeMismatch(get_class($owner), $mapping['name'], $key, 'array', gettype($reference));
}
$identifier = ClassMetadata::getReferenceId($reference, $mapping['storeAs']);
$id = $this->dm->getClassMetadata($className)->getPHPIdentifierValue($identifier);
// create a reference to the class and id
$reference = $this->dm->getReference($className, $id);
// no custom sort so add the references right now in the order they are embedded
if (! $sorted) {
if (CollectionHelper::isHash($mapping['strategy'])) {
$collection->set($key, $reference);
} else {
$collection->add($reference);
}
}
// only query for the referenced object if it is not already initialized or the collection is sorted
if (! (($reference instanceof GhostObjectInterface && ! $reference->isProxyInitialized())) && ! $sorted) {
continue;
}
$groupedIds[$className][] = $identifier;
}
foreach ($groupedIds as $className => $ids) {
$class = $this->dm->getClassMetadata($className);
$mongoCollection = $this->dm->getDocumentCollection($className);
$criteria = $this->cm->merge(
['_id' => ['$in' => array_values($ids)]],
$this->dm->getFilterCollection()->getFilterCriteria($class),
$mapping['criteria'] ?? []
);
$criteria = $this->uow->getDocumentPersister($className)->prepareQueryOrNewObj($criteria);
$options = [];
if (isset($mapping['sort'])) {
$options['sort'] = $this->prepareSort($mapping['sort']);
}
if (isset($mapping['limit'])) {
$options['limit'] = $mapping['limit'];
}
if (isset($mapping['skip'])) {
$options['skip'] = $mapping['skip'];
}
if (! empty($hints[Query::HINT_READ_PREFERENCE])) {
$options['readPreference'] = $hints[Query::HINT_READ_PREFERENCE];
}
$cursor = $mongoCollection->find($criteria, $options);
$documents = $cursor->toArray();
foreach ($documents as $documentData) {
$document = $this->uow->getById($documentData['_id'], $class);
if ($document instanceof GhostObjectInterface && ! $document->isProxyInitialized()) {
$data = $this->hydratorFactory->hydrate($document, $documentData);
$this->uow->setOriginalDocumentData($document, $data);
}
if (! $sorted) {
continue;
}
$collection->add($document);
}
}
}
private function loadReferenceManyCollectionInverseSide(PersistentCollectionInterface $collection): void
{
$query = $this->createReferenceManyInverseSideQuery($collection);
$iterator = $query->execute();
assert($iterator instanceof Iterator);
$documents = $iterator->toArray();
foreach ($documents as $key => $document) {
$collection->add($document);
}
}
public function createReferenceManyInverseSideQuery(PersistentCollectionInterface $collection): Query
{
$hints = $collection->getHints();
$mapping = $collection->getMapping();
$owner = $collection->getOwner();
if ($owner === null) {
throw PersistentCollectionException::ownerRequiredToLoadCollection();
}
$ownerClass = $this->dm->getClassMetadata(get_class($owner));
$targetClass = $this->dm->getClassMetadata($mapping['targetDocument']);
$mappedByMapping = $targetClass->fieldMappings[$mapping['mappedBy']] ?? [];
$mappedByFieldName = ClassMetadata::getReferenceFieldName($mappedByMapping['storeAs'] ?? ClassMetadata::REFERENCE_STORE_AS_DB_REF, $mapping['mappedBy']);
$criteria = $this->cm->merge(
[$mappedByFieldName => $ownerClass->getIdentifierObject($owner)],
$this->dm->getFilterCollection()->getFilterCriteria($targetClass),
$mapping['criteria'] ?? []
);
$criteria = $this->uow->getDocumentPersister($mapping['targetDocument'])->prepareQueryOrNewObj($criteria);
$qb = $this->dm->createQueryBuilder($mapping['targetDocument'])
->setQueryArray($criteria);
if (isset($mapping['sort'])) {
$qb->sort($mapping['sort']);
}
if (isset($mapping['limit'])) {
$qb->limit($mapping['limit']);
}
if (isset($mapping['skip'])) {
$qb->skip($mapping['skip']);
}
if (! empty($hints[Query::HINT_READ_PREFERENCE])) {
$qb->setReadPreference($hints[Query::HINT_READ_PREFERENCE]);
}
foreach ($mapping['prime'] as $field) {
$qb->field($field)->prime(true);
}
return $qb->getQuery();
}
private function loadReferenceManyWithRepositoryMethod(PersistentCollectionInterface $collection): void
{
$cursor = $this->createReferenceManyWithRepositoryMethodCursor($collection);
$mapping = $collection->getMapping();
$documents = $cursor->toArray();
foreach ($documents as $key => $obj) {
if (CollectionHelper::isHash($mapping['strategy'])) {
$collection->set($key, $obj);
} else {
$collection->add($obj);
}
}
}
public function createReferenceManyWithRepositoryMethodCursor(PersistentCollectionInterface $collection): Iterator
{
$mapping = $collection->getMapping();
$repositoryMethod = $mapping['repositoryMethod'];
$cursor = $this->dm->getRepository($mapping['targetDocument'])
->$repositoryMethod($collection->getOwner());
if (! $cursor instanceof Iterator) {
throw new BadMethodCallException(sprintf('Expected repository method %s to return an iterable object', $repositoryMethod));
}
if (! empty($mapping['prime'])) {
$referencePrimer = new ReferencePrimer($this->dm, $this->dm->getUnitOfWork());
$primers = array_combine($mapping['prime'], array_fill(0, count($mapping['prime']), true));
$class = $this->dm->getClassMetadata($mapping['targetDocument']);
assert(is_array($primers));
$cursor = new PrimingIterator($cursor, $class, $referencePrimer, $primers, $collection->getHints());
}
return $cursor;
}
/**
* Prepare a projection array by converting keys, which are PHP property
* names, to MongoDB field names.
*/
public function prepareProjection(array $fields): array
{
$preparedFields = [];
foreach ($fields as $key => $value) {
$preparedFields[$this->prepareFieldName($key)] = $value;
}
return $preparedFields;
}
/**
* @param int|string|null $sort
*
* @return int|string|null
*/
private function getSortDirection($sort)
{
switch (strtolower((string) $sort)) {
case 'desc':
return -1;
case 'asc':
return 1;
}
return $sort;
}
/**
* Prepare a sort specification array by converting keys to MongoDB field
* names and changing direction strings to int.
*/
public function prepareSort(array $fields): array
{
$sortFields = [];
foreach ($fields as $key => $value) {
if (is_array($value)) {
$sortFields[$this->prepareFieldName($key)] = $value;
} else {
$sortFields[$this->prepareFieldName($key)] = $this->getSortDirection($value);
}
}
return $sortFields;
}
/**
* Prepare a mongodb field name and convert the PHP property names to
* MongoDB field names.
*/
public function prepareFieldName(string $fieldName): string
{
$fieldNames = $this->prepareQueryElement($fieldName, null, null, false);
return $fieldNames[0][0];
}
/**
* Adds discriminator criteria to an already-prepared query.
*
* If the class we're querying has a discriminator field set, we add all
* possible discriminator values to the query. The list of possible
* discriminator values is based on the discriminatorValue of the class
* itself as well as those of all its subclasses.
*
* This method should be used once for query criteria and not be used for
* nested expressions. It should be called before
* {@link DocumentPerister::addFilterToPreparedQuery()}.
*/
public function addDiscriminatorToPreparedQuery(array $preparedQuery): array
{
if (isset($preparedQuery[$this->class->discriminatorField]) || $this->class->discriminatorField === null) {
return $preparedQuery;
}
$discriminatorValues = $this->getClassDiscriminatorValues($this->class);
if ($discriminatorValues === []) {
return $preparedQuery;
}
if (count($discriminatorValues) === 1) {
$preparedQuery[$this->class->discriminatorField] = $discriminatorValues[0];
} else {
$preparedQuery[$this->class->discriminatorField] = ['$in' => $discriminatorValues];
}
return $preparedQuery;
}
/**
* Adds filter criteria to an already-prepared query.
*
* This method should be used once for query criteria and not be used for
* nested expressions. It should be called after
* {@link DocumentPerister::addDiscriminatorToPreparedQuery()}.
*/
public function addFilterToPreparedQuery(array $preparedQuery): array
{
/* If filter criteria exists for this class, prepare it and merge
* over the existing query.
*
* @todo Consider recursive merging in case the filter criteria and
* prepared query both contain top-level $and/$or operators.
*/
$filterCriteria = $this->dm->getFilterCollection()->getFilterCriteria($this->class);
if ($filterCriteria) {