-
-
Notifications
You must be signed in to change notification settings - Fork 506
/
Copy pathDocumentManager.php
898 lines (779 loc) · 28.5 KB
/
DocumentManager.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
<?php
declare(strict_types=1);
namespace Doctrine\ODM\MongoDB;
use Doctrine\Common\EventManager;
use Doctrine\ODM\MongoDB\Hydrator\HydratorFactory;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataFactoryInterface;
use Doctrine\ODM\MongoDB\Mapping\MappingException;
use Doctrine\ODM\MongoDB\Proxy\Factory\ProxyFactory;
use Doctrine\ODM\MongoDB\Proxy\Factory\StaticProxyFactory;
use Doctrine\ODM\MongoDB\Proxy\Resolver\CachingClassNameResolver;
use Doctrine\ODM\MongoDB\Proxy\Resolver\ClassNameResolver;
use Doctrine\ODM\MongoDB\Proxy\Resolver\ProxyManagerClassNameResolver;
use Doctrine\ODM\MongoDB\Query\FilterCollection;
use Doctrine\ODM\MongoDB\Repository\DocumentRepository;
use Doctrine\ODM\MongoDB\Repository\GridFSRepository;
use Doctrine\ODM\MongoDB\Repository\RepositoryFactory;
use Doctrine\ODM\MongoDB\Repository\ViewRepository;
use Doctrine\Persistence\Mapping\ProxyClassNameResolver;
use Doctrine\Persistence\ObjectManager;
use InvalidArgumentException;
use Jean85\PrettyVersions;
use MongoDB\Client;
use MongoDB\Collection;
use MongoDB\Database;
use MongoDB\Driver\ReadPreference;
use MongoDB\GridFS\Bucket;
use ProxyManager\Proxy\GhostObjectInterface;
use RuntimeException;
use Throwable;
use function array_search;
use function assert;
use function gettype;
use function is_object;
use function ltrim;
use function sprintf;
use function trigger_deprecation;
/**
* The DocumentManager class is the central access point for managing the
* persistence of documents.
*
* <?php
*
* $config = new Configuration();
* $dm = DocumentManager::create(new Connection(), $config);
*
* @psalm-import-type CommitOptions from UnitOfWork
* @psalm-import-type FieldMapping from ClassMetadata
*/
class DocumentManager implements ObjectManager
{
public const CLIENT_TYPEMAP = ['root' => 'array', 'document' => 'array'];
/**
* The Doctrine MongoDB connection instance.
*/
private Client $client;
/**
* The used Configuration.
*/
private Configuration $config;
/**
* The metadata factory, used to retrieve the ODM metadata of document classes.
*/
private ClassMetadataFactoryInterface $metadataFactory;
/**
* The UnitOfWork used to coordinate object-level transactions.
*/
private UnitOfWork $unitOfWork;
/**
* The event manager that is the central point of the event system.
*/
private EventManager $eventManager;
/**
* The Hydrator factory instance.
*/
private HydratorFactory $hydratorFactory;
/**
* The Proxy factory instance.
*/
private ProxyFactory $proxyFactory;
/**
* The repository factory used to create dynamic repositories.
*/
private RepositoryFactory $repositoryFactory;
/**
* SchemaManager instance
*/
private SchemaManager $schemaManager;
/**
* Array of cached document database instances that are lazily loaded.
*
* @var Database[]
*/
private array $documentDatabases = [];
/**
* Array of cached document collection instances that are lazily loaded.
*
* @var Collection[]
*/
private array $documentCollections = [];
/**
* Array of cached document bucket instances that are lazily loaded.
*
* @var Bucket[]
*/
private array $documentBuckets = [];
/**
* Whether the DocumentManager is closed or not.
*/
private bool $closed = false;
/**
* Collection of query filters.
*/
private ?FilterCollection $filterCollection = null;
/** @var ProxyClassNameResolver&ClassNameResolver */
private ProxyClassNameResolver $classNameResolver;
private static ?string $version = null;
/**
* Creates a new Document that operates on the given Mongo connection
* and uses the given Configuration.
*/
protected function __construct(?Client $client = null, ?Configuration $config = null, ?EventManager $eventManager = null)
{
$this->config = $config ?: new Configuration();
$this->eventManager = $eventManager ?: new EventManager();
$this->client = $client ?: new Client(
'mongodb://127.0.0.1',
[],
[
'driver' => [
'name' => 'doctrine-odm',
'version' => self::getVersion(),
],
],
);
$this->classNameResolver = new CachingClassNameResolver(new ProxyManagerClassNameResolver($this->config));
$metadataFactoryClassName = $this->config->getClassMetadataFactoryName();
$this->metadataFactory = new $metadataFactoryClassName();
$this->metadataFactory->setDocumentManager($this);
$this->metadataFactory->setConfiguration($this->config);
$this->metadataFactory->setProxyClassNameResolver($this->classNameResolver);
$cacheDriver = $this->config->getMetadataCache();
if ($cacheDriver) {
$this->metadataFactory->setCache($cacheDriver);
}
$hydratorDir = $this->config->getHydratorDir();
$hydratorNs = $this->config->getHydratorNamespace();
$this->hydratorFactory = new HydratorFactory(
$this,
$this->eventManager,
$hydratorDir,
$hydratorNs,
$this->config->getAutoGenerateHydratorClasses(),
);
$this->unitOfWork = new UnitOfWork($this, $this->eventManager, $this->hydratorFactory);
$this->hydratorFactory->setUnitOfWork($this->unitOfWork);
$this->schemaManager = new SchemaManager($this, $this->metadataFactory);
$this->proxyFactory = new StaticProxyFactory($this);
$this->repositoryFactory = $this->config->getRepositoryFactory();
}
/**
* Gets the proxy factory used by the DocumentManager to create document proxies.
*/
public function getProxyFactory(): ProxyFactory
{
return $this->proxyFactory;
}
/**
* Creates a new Document that operates on the given Mongo connection
* and uses the given Configuration.
*/
public static function create(?Client $client = null, ?Configuration $config = null, ?EventManager $eventManager = null): DocumentManager
{
return new static($client, $config, $eventManager);
}
/**
* Gets the EventManager used by the DocumentManager.
*/
public function getEventManager(): EventManager
{
return $this->eventManager;
}
/**
* Gets the MongoDB client instance that this DocumentManager wraps.
*/
public function getClient(): Client
{
return $this->client;
}
/**
* Gets the metadata factory used to gather the metadata of classes.
*
* @return ClassMetadataFactoryInterface
*/
public function getMetadataFactory()
{
return $this->metadataFactory;
}
/**
* Helper method to initialize a lazy loading proxy or persistent collection.
*
* This method is a no-op for other objects.
*
* @param object $obj
*/
public function initializeObject($obj)
{
$this->unitOfWork->initializeObject($obj);
}
/**
* Helper method to check whether a lazy loading proxy or persistent collection has been initialized.
*/
public function isUninitializedObject(object $obj): bool
{
return $this->unitOfWork->isUninitializedObject($obj);
}
/**
* Gets the UnitOfWork used by the DocumentManager to coordinate operations.
*/
public function getUnitOfWork(): UnitOfWork
{
return $this->unitOfWork;
}
/**
* Gets the Hydrator factory used by the DocumentManager to generate and get hydrators
* for each type of document.
*/
public function getHydratorFactory(): HydratorFactory
{
return $this->hydratorFactory;
}
/**
* Returns SchemaManager, used to create/drop indexes/collections/databases.
*/
public function getSchemaManager(): SchemaManager
{
return $this->schemaManager;
}
/**
* Returns the class name resolver which is used to resolve real class names for proxy objects.
*
* @deprecated Fetch metadata for any class string (e.g. proxy object class) and read the class name from the metadata object
*/
public function getClassNameResolver(): ClassNameResolver
{
return $this->classNameResolver;
}
/**
* Returns the metadata for a class.
*
* @param string $className The class name.
* @psalm-param class-string<T> $className
*
* @psalm-return ClassMetadata<T>
*
* @template T of object
*
* @psalm-suppress InvalidReturnType, InvalidReturnStatement see https://github.com/vimeo/psalm/issues/5788
*/
public function getClassMetadata($className): ClassMetadata
{
return $this->metadataFactory->getMetadataFor($className);
}
/**
* Returns the MongoDB instance for a class.
*
* @psalm-param class-string $className
*/
public function getDocumentDatabase(string $className): Database
{
$metadata = $this->metadataFactory->getMetadataFor($className);
$className = $metadata->getName();
if (isset($this->documentDatabases[$className])) {
return $this->documentDatabases[$className];
}
$db = $metadata->getDatabase();
$db = $db ?: $this->config->getDefaultDB();
$db = $db ?: 'doctrine';
$this->documentDatabases[$className] = $this->client->selectDatabase($db);
return $this->documentDatabases[$className];
}
/**
* Gets the array of instantiated document database instances.
*
* @return Database[]
*/
public function getDocumentDatabases(): array
{
return $this->documentDatabases;
}
/**
* Returns the collection instance for a class.
*
* @throws MongoDBException When the $className param is not mapped to a collection.
*/
public function getDocumentCollection(string $className): Collection
{
$metadata = $this->metadataFactory->getMetadataFor($className);
if ($metadata->isFile) {
return $this->getDocumentBucket($className)->getFilesCollection();
}
$collectionName = $metadata->getCollection();
if (! $collectionName) {
throw MongoDBException::documentNotMappedToCollection($className);
}
if (! isset($this->documentCollections[$className])) {
$db = $this->getDocumentDatabase($className);
$options = ['typeMap' => self::CLIENT_TYPEMAP];
if ($metadata->readPreference !== null) {
$options['readPreference'] = new ReadPreference($metadata->readPreference, $metadata->readPreferenceTags);
}
$this->documentCollections[$className] = $db->selectCollection($collectionName, $options);
}
return $this->documentCollections[$className];
}
/**
* Returns the bucket instance for a class.
*
* @throws MongoDBException When the $className param is not mapped to a collection.
*/
public function getDocumentBucket(string $className): Bucket
{
$metadata = $this->metadataFactory->getMetadataFor($className);
if (! $metadata->isFile) {
throw MongoDBException::documentBucketOnlyAvailableForGridFSFiles($className);
}
$bucketName = $metadata->getBucketName();
if (! $bucketName) {
throw MongoDBException::documentNotMappedToCollection($className);
}
if (! isset($this->documentBuckets[$className])) {
$db = $this->getDocumentDatabase($className);
$options = ['bucketName' => $bucketName, 'typeMap' => self::CLIENT_TYPEMAP];
if ($metadata->readPreference !== null) {
$options['readPreference'] = new ReadPreference($metadata->readPreference, $metadata->readPreferenceTags);
}
$this->documentBuckets[$className] = $db->selectGridFSBucket($options);
}
return $this->documentBuckets[$className];
}
/**
* Gets the array of instantiated document collection instances.
*
* @return Collection[]
*/
public function getDocumentCollections(): array
{
return $this->documentCollections;
}
/**
* Create a new Query instance for a class.
*
* @param string[]|string|null $documentName (optional) an array of document names, the document name, or none
*/
public function createQueryBuilder($documentName = null): Query\Builder
{
return new Query\Builder($this, $documentName);
}
/**
* Creates a new aggregation builder instance for a class.
*/
public function createAggregationBuilder(string $documentName): Aggregation\Builder
{
return new Aggregation\Builder($this, $documentName);
}
/**
* Tells the DocumentManager to make an instance managed and persistent.
*
* The document will be entered into the database at or before transaction
* commit or as a result of the flush operation.
*
* NOTE: The persist operation always considers documents that are not yet known to
* this DocumentManager as NEW. Do not pass detached documents to the persist operation.
*
* @param object $object The instance to make managed and persistent.
*
* @throws InvalidArgumentException When the given $object param is not an object.
*/
public function persist($object)
{
if (! is_object($object)) {
throw new InvalidArgumentException(gettype($object));
}
$this->errorIfClosed();
$this->unitOfWork->persist($object);
}
/**
* Removes a document instance.
*
* A removed document will be removed from the database at or before transaction commit
* or as a result of the flush operation.
*
* @param object $object The document instance to remove.
*
* @throws InvalidArgumentException When the $object param is not an object.
*/
public function remove($object)
{
if (! is_object($object)) {
throw new InvalidArgumentException(gettype($object));
}
$this->errorIfClosed();
$this->unitOfWork->remove($object);
}
/**
* Refreshes the persistent state of a document from the database,
* overriding any local changes that have not yet been persisted.
*
* @param object $object The document to refresh.
*
* @throws InvalidArgumentException When the given $object param is not an object.
*/
public function refresh($object)
{
if (! is_object($object)) {
throw new InvalidArgumentException(gettype($object));
}
$this->errorIfClosed();
$this->unitOfWork->refresh($object);
}
/**
* Detaches a document from the DocumentManager, causing a managed document to
* become detached. Unflushed changes made to the document if any
* (including removal of the document), will not be synchronized to the database.
* Documents which previously referenced the detached document will continue to
* reference it.
*
* @param object $object The document to detach.
*
* @throws InvalidArgumentException When the $object param is not an object.
*/
public function detach($object)
{
if (! is_object($object)) {
throw new InvalidArgumentException(gettype($object));
}
$this->unitOfWork->detach($object);
}
/**
* Merges the state of a detached document into the persistence context
* of this DocumentManager and returns the managed copy of the document.
* The document passed to merge will not become associated/managed with this DocumentManager.
*
* @param object $object The detached document to merge into the persistence context.
*
* @return object The managed copy of the document.
*
* @throws LockException
* @throws InvalidArgumentException If the $object param is not an object.
*/
public function merge($object)
{
if (! is_object($object)) {
throw new InvalidArgumentException(gettype($object));
}
$this->errorIfClosed();
return $this->unitOfWork->merge($object);
}
/**
* Acquire a lock on the given document.
*
* @throws InvalidArgumentException
* @throws LockException
*/
public function lock(object $document, int $lockMode, ?int $lockVersion = null): void
{
$this->unitOfWork->lock($document, $lockMode, $lockVersion);
}
/**
* Releases a lock on the given document.
*/
public function unlock(object $document): void
{
$this->unitOfWork->unlock($document);
}
/**
* Gets the repository for a document class.
*
* @param string $className The name of the Document.
* @psalm-param class-string<T> $className
*
* @return DocumentRepository|GridFSRepository|ViewRepository The repository.
* @psalm-return DocumentRepository<T>|GridFSRepository<T>|ViewRepository<T>
*
* @template T of object
*/
public function getRepository($className)
{
return $this->repositoryFactory->getRepository($this, $className);
}
/**
* Flushes all changes to objects that have been queued up to now to the database.
* This effectively synchronizes the in-memory state of managed objects with the
* database.
*
* @param array $options Array of options to be used with batchInsert(), update() and remove()
* @psalm-param CommitOptions $options
*
* @throws MongoDBException
*/
public function flush(array $options = [])
{
$this->errorIfClosed();
$this->unitOfWork->commit($options);
}
/**
* Gets a reference to the document identified by the given type and identifier
* without actually loading it.
*
* If partial objects are allowed, this method will return a partial object that only
* has its identifier populated. Otherwise a proxy is returned that automatically
* loads itself on first access.
*
* @param mixed $identifier
* @psalm-param class-string<T> $documentName
*
* @psalm-return T|(T&GhostObjectInterface<T>)
*
* @template T of object
*/
public function getReference(string $documentName, $identifier): object
{
/** @psalm-var ClassMetadata<T> $class */
$class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
assert($class instanceof ClassMetadata);
/** @psalm-var T|false $document */
$document = $this->unitOfWork->tryGetById($identifier, $class);
// Check identity map first, if its already in there just return it.
if ($document !== false) {
return $document;
}
/** @psalm-var T&GhostObjectInterface<T> $document */
$document = $this->proxyFactory->getProxy($class, $identifier);
$this->unitOfWork->registerManaged($document, $identifier, []);
return $document;
}
/**
* Gets a partial reference to the document identified by the given type and identifier
* without actually loading it, if the document is not yet loaded.
*
* The returned reference may be a partial object if the document is not yet loaded/managed.
* If it is a partial object it will not initialize the rest of the document state on access.
* Thus you can only ever safely access the identifier of a document obtained through
* this method.
*
* The use-cases for partial references involve maintaining bidirectional associations
* without loading one side of the association or to update a document without loading it.
* Note, however, that in the latter case the original (persistent) document data will
* never be visible to the application (especially not event listeners) as it will
* never be loaded in the first place.
*
* @param mixed $identifier The document identifier.
*/
public function getPartialReference(string $documentName, $identifier): object
{
$class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
$document = $this->unitOfWork->tryGetById($identifier, $class);
// Check identity map first, if its already in there just return it.
if ($document) {
return $document;
}
$document = $class->newInstance();
$class->setIdentifierValue($document, $identifier);
$this->unitOfWork->registerManaged($document, $identifier, []);
return $document;
}
/**
* Finds a Document by its identifier.
*
* This is just a convenient shortcut for getRepository($documentName)->find($id).
*
* @param string $className
* @param mixed $id
* @param int $lockMode
* @param int $lockVersion
* @psalm-param class-string<T> $className
*
* @psalm-return T|null
*
* @template T of object
*/
public function find($className, $id, $lockMode = LockMode::NONE, $lockVersion = null): ?object
{
$repository = $this->getRepository($className);
if ($repository instanceof DocumentRepository) {
/** @psalm-var DocumentRepository<T> $repository */
return $repository->find($id, $lockMode, $lockVersion);
}
return $repository->find($id);
}
/**
* Clears the DocumentManager.
*
* All documents that are currently managed by this DocumentManager become
* detached.
*
* @param string|null $objectName if given, only documents of this type will get detached
*/
public function clear($objectName = null)
{
if ($objectName !== null) {
trigger_deprecation(
'doctrine/mongodb-odm',
'2.4',
'Calling %s() with any arguments to clear specific documents is deprecated and will not be supported in Doctrine ODM 3.0.',
__METHOD__,
);
}
$this->unitOfWork->clear($objectName);
}
/**
* Closes the DocumentManager. All documents that are currently managed
* by this DocumentManager become detached. The DocumentManager may no longer
* be used after it is closed.
*
* @return void
*/
public function close()
{
$this->clear();
$this->closed = true;
}
/**
* Determines whether a document instance is managed in this DocumentManager.
*
* @param object $object
*
* @return bool TRUE if this DocumentManager currently manages the given document, FALSE otherwise.
*
* @throws InvalidArgumentException When the $object param is not an object.
*/
public function contains($object)
{
if (! is_object($object)) {
throw new InvalidArgumentException(gettype($object));
}
return $this->unitOfWork->isScheduledForInsert($object) ||
$this->unitOfWork->isInIdentityMap($object) &&
! $this->unitOfWork->isScheduledForDelete($object);
}
/**
* Gets the Configuration used by the DocumentManager.
*/
public function getConfiguration(): Configuration
{
return $this->config;
}
/**
* Returns a reference to the supplied document.
*
* @psalm-param FieldMapping $referenceMapping
*
* @return mixed The reference for the document in question, according to the desired mapping
*
* @throws MappingException
* @throws RuntimeException
*/
public function createReference(object $document, array $referenceMapping)
{
$class = $this->getClassMetadata($document::class);
$id = $this->unitOfWork->getDocumentIdentifier($document);
if ($id === null) {
throw new RuntimeException(
sprintf('Cannot create a DBRef for class %s without an identifier. Have you forgotten to persist/merge the document first?', $class->name),
);
}
$storeAs = $referenceMapping['storeAs'] ?? null;
switch ($storeAs) {
case ClassMetadata::REFERENCE_STORE_AS_ID:
if ($class->inheritanceType === ClassMetadata::INHERITANCE_TYPE_SINGLE_COLLECTION) {
throw MappingException::simpleReferenceMustNotTargetDiscriminatedDocument($referenceMapping['targetDocument']);
}
return $class->getDatabaseIdentifierValue($id);
case ClassMetadata::REFERENCE_STORE_AS_REF:
$reference = ['id' => $class->getDatabaseIdentifierValue($id)];
break;
case ClassMetadata::REFERENCE_STORE_AS_DB_REF:
$reference = [
'$ref' => $class->getCollection(),
'$id' => $class->getDatabaseIdentifierValue($id),
];
break;
case ClassMetadata::REFERENCE_STORE_AS_DB_REF_WITH_DB:
$reference = [
'$ref' => $class->getCollection(),
'$id' => $class->getDatabaseIdentifierValue($id),
'$db' => $this->getDocumentDatabase($class->name)->getDatabaseName(),
];
break;
default:
throw new InvalidArgumentException(sprintf('Reference type %s is invalid.', $storeAs));
}
return $reference + $this->getDiscriminatorData($referenceMapping, $class);
}
/**
* Build discriminator portion of reference for specified reference mapping and class metadata.
*
* @param array $referenceMapping Mappings of reference for which discriminator data is created.
* @param ClassMetadata<object> $class Metadata of reference document class.
* @psalm-param FieldMapping $referenceMapping
*
* @return array with next structure [{discriminator field} => {discriminator value}]
* @psalm-return array<string, class-string>
*
* @throws MappingException When discriminator map is present and reference class in not registered in it.
*/
private function getDiscriminatorData(array $referenceMapping, ClassMetadata $class): array
{
$discriminatorField = null;
$discriminatorValue = null;
$discriminatorMap = null;
if (isset($referenceMapping['discriminatorField'])) {
$discriminatorField = $referenceMapping['discriminatorField'];
if (isset($referenceMapping['discriminatorMap'])) {
$discriminatorMap = $referenceMapping['discriminatorMap'];
}
} else {
$discriminatorField = $class->discriminatorField;
$discriminatorValue = $class->discriminatorValue;
$discriminatorMap = $class->discriminatorMap;
}
if ($discriminatorField === null) {
return [];
}
if ($discriminatorValue === null) {
if (! empty($discriminatorMap)) {
$pos = array_search($class->name, $discriminatorMap);
if ($pos !== false) {
$discriminatorValue = $pos;
}
} else {
$discriminatorValue = $class->name;
}
}
if ($discriminatorValue === null) {
throw MappingException::unlistedClassInDiscriminatorMap($class->name);
}
return [$discriminatorField => $discriminatorValue];
}
/**
* Throws an exception if the DocumentManager is closed or currently not active.
*
* @throws MongoDBException If the DocumentManager is closed.
*/
private function errorIfClosed(): void
{
if ($this->closed) {
throw MongoDBException::documentManagerClosed();
}
}
/**
* Check if the Document manager is open or closed.
*/
public function isOpen(): bool
{
return ! $this->closed;
}
/**
* Gets the filter collection.
*/
public function getFilterCollection(): FilterCollection
{
if ($this->filterCollection === null) {
$this->filterCollection = new FilterCollection($this);
}
return $this->filterCollection;
}
private static function getVersion(): string
{
if (self::$version === null) {
try {
self::$version = PrettyVersions::getVersion('doctrine/mongodb-odm')->getPrettyVersion();
} catch (Throwable) {
return 'unknown';
}
}
return self::$version;
}
}