Completed
Pull Request — master (#1803)
by Maciej
21:27
created

DocumentManager::unlock()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
ccs 3
cts 4
cp 0.75
cc 2
eloc 4
nc 2
nop 1
crap 2.0625
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ODM\MongoDB;
6
7
use Doctrine\Common\EventManager;
8
use Doctrine\Common\Persistence\ObjectManager;
9
use Doctrine\Common\Persistence\ObjectRepository;
10
use Doctrine\ODM\MongoDB\Hydrator\HydratorFactory;
11
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
12
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataFactory;
13
use Doctrine\ODM\MongoDB\Mapping\MappingException;
14
use Doctrine\ODM\MongoDB\Proxy\ProxyFactory;
15
use Doctrine\ODM\MongoDB\Query\FilterCollection;
16
use Doctrine\ODM\MongoDB\Repository\RepositoryFactory;
17
use MongoDB\Client;
18
use MongoDB\Collection;
19
use MongoDB\Database;
20
use MongoDB\Driver\ReadPreference;
21
use function array_search;
22
use function get_class;
23
use function gettype;
24
use function is_object;
25
use function ltrim;
26
use function sprintf;
27
28
/**
29
 * The DocumentManager class is the central access point for managing the
30
 * persistence of documents.
31
 *
32
 *     <?php
33
 *
34
 *     $config = new Configuration();
35
 *     $dm = DocumentManager::create(new Connection(), $config);
36
 *
37
 */
38
class DocumentManager implements ObjectManager
39
{
40
    /**
41
     * The Doctrine MongoDB connection instance.
42
     *
43
     * @var Client
44
     */
45
    private $client;
46
47
    /**
48
     * The used Configuration.
49
     *
50
     * @var Configuration
51
     */
52
    private $config;
53
54
    /**
55
     * The metadata factory, used to retrieve the ODM metadata of document classes.
56
     *
57
     * @var ClassMetadataFactory
58
     */
59
    private $metadataFactory;
60
61
    /**
62
     * The UnitOfWork used to coordinate object-level transactions.
63
     *
64
     * @var UnitOfWork
65
     */
66
    private $unitOfWork;
67
68
    /**
69
     * The event manager that is the central point of the event system.
70
     *
71
     * @var EventManager
72
     */
73
    private $eventManager;
74
75
    /**
76
     * The Hydrator factory instance.
77
     *
78
     * @var HydratorFactory
79
     */
80
    private $hydratorFactory;
81
82
    /**
83
     * The Proxy factory instance.
84
     *
85
     * @var ProxyFactory
86
     */
87
    private $proxyFactory;
88
89
    /**
90
     * The repository factory used to create dynamic repositories.
91
     *
92
     * @var RepositoryFactory
93
     */
94
    private $repositoryFactory;
95
96
    /**
97
     * SchemaManager instance
98
     *
99
     * @var SchemaManager
100
     */
101
    private $schemaManager;
102
103
    /**
104
     * Array of cached document database instances that are lazily loaded.
105
     *
106
     * @var Database[]
107
     */
108
    private $documentDatabases = [];
109
110
    /**
111
     * Array of cached document collection instances that are lazily loaded.
112
     *
113
     * @var Collection[]
114
     */
115
    private $documentCollections = [];
116
117
    /**
118
     * Whether the DocumentManager is closed or not.
119
     *
120
     * @var bool
121
     */
122
    private $closed = false;
123
124
    /**
125
     * Collection of query filters.
126
     *
127
     * @var FilterCollection
128
     */
129
    private $filterCollection;
130
131
    /**
132
     * Creates a new Document that operates on the given Mongo connection
133
     * and uses the given Configuration.
134
     *
135
     */
136 1584
    protected function __construct(?Client $client = null, ?Configuration $config = null, ?EventManager $eventManager = null)
137
    {
138 1584
        $this->config = $config ?: new Configuration();
139 1584
        $this->eventManager = $eventManager ?: new EventManager();
140 1584
        $this->client = $client ?: new Client('mongodb://127.0.0.1', [], ['typeMap' => ['root' => 'array', 'document' => 'array']]);
141
142 1584
        $metadataFactoryClassName = $this->config->getClassMetadataFactoryName();
143 1584
        $this->metadataFactory = new $metadataFactoryClassName();
144 1584
        $this->metadataFactory->setDocumentManager($this);
145 1584
        $this->metadataFactory->setConfiguration($this->config);
146
147 1584
        $cacheDriver = $this->config->getMetadataCacheImpl();
148 1584
        if ($cacheDriver) {
149
            $this->metadataFactory->setCacheDriver($cacheDriver);
150
        }
151
152 1584
        $hydratorDir = $this->config->getHydratorDir();
153 1584
        $hydratorNs = $this->config->getHydratorNamespace();
154 1584
        $this->hydratorFactory = new HydratorFactory(
155 1584
            $this,
156 1584
            $this->eventManager,
157 1584
            $hydratorDir,
158 1584
            $hydratorNs,
159 1584
            $this->config->getAutoGenerateHydratorClasses()
160
        );
161
162 1584
        $this->unitOfWork = new UnitOfWork($this, $this->eventManager, $this->hydratorFactory);
163 1584
        $this->hydratorFactory->setUnitOfWork($this->unitOfWork);
164 1584
        $this->schemaManager = new SchemaManager($this, $this->metadataFactory);
165 1584
        $this->proxyFactory = new ProxyFactory(
166 1584
            $this,
167 1584
            $this->config->getProxyDir(),
168 1584
            $this->config->getProxyNamespace(),
169 1584
            $this->config->getAutoGenerateProxyClasses()
170
        );
171 1584
        $this->repositoryFactory = $this->config->getRepositoryFactory();
172 1584
    }
173
174
    /**
175
     * Gets the proxy factory used by the DocumentManager to create document proxies.
176
     *
177
     * @return ProxyFactory
178
     */
179 1
    public function getProxyFactory()
180
    {
181 1
        return $this->proxyFactory;
182
    }
183
184
    /**
185
     * Creates a new Document that operates on the given Mongo connection
186
     * and uses the given Configuration.
187
     *
188
     * @static
189
     * @return DocumentManager
190
     */
191 1584
    public static function create(?Client $client = null, ?Configuration $config = null, ?EventManager $eventManager = null)
192
    {
193 1584
        return new static($client, $config, $eventManager);
194
    }
195
196
    /**
197
     * Gets the EventManager used by the DocumentManager.
198
     *
199
     * @return EventManager
200
     */
201 1627
    public function getEventManager()
202
    {
203 1627
        return $this->eventManager;
204
    }
205
206
    /**
207
     * Gets the MongoDB client instance that this DocumentManager wraps.
208
     *
209
     * @return Client
210
     */
211 1584
    public function getClient()
212
    {
213 1584
        return $this->client;
214
    }
215
216
    /**
217
     * Gets the metadata factory used to gather the metadata of classes.
218
     *
219
     * @return ClassMetadataFactory
220
     */
221 1584
    public function getMetadataFactory()
222
    {
223 1584
        return $this->metadataFactory;
224
    }
225
226
    /**
227
     * Helper method to initialize a lazy loading proxy or persistent collection.
228
     *
229
     * This method is a no-op for other objects.
230
     *
231
     * @param object $obj
232
     */
233
    public function initializeObject($obj)
234
    {
235
        $this->unitOfWork->initializeObject($obj);
236
    }
237
238
    /**
239
     * Gets the UnitOfWork used by the DocumentManager to coordinate operations.
240
     *
241
     * @return UnitOfWork
242
     */
243 1590
    public function getUnitOfWork()
244
    {
245 1590
        return $this->unitOfWork;
246
    }
247
248
    /**
249
     * Gets the Hydrator factory used by the DocumentManager to generate and get hydrators
250
     * for each type of document.
251
     *
252
     * @return HydratorFactory
253
     */
254 66
    public function getHydratorFactory()
255
    {
256 66
        return $this->hydratorFactory;
257
    }
258
259
    /**
260
     * Returns SchemaManager, used to create/drop indexes/collections/databases.
261
     *
262
     * @return SchemaManager
263
     */
264 19
    public function getSchemaManager()
265
    {
266 19
        return $this->schemaManager;
267
    }
268
269
    /**
270
     * Returns the metadata for a class.
271
     *
272
     * @param string $className The class name.
273
     * @return ClassMetadata
274
     * @internal Performance-sensitive method.
275
     */
276 1323
    public function getClassMetadata($className)
277
    {
278 1323
        return $this->metadataFactory->getMetadataFor(ltrim($className, '\\'));
279
    }
280
281
    /**
282
     * Returns the MongoDB instance for a class.
283
     *
284
     * @param string $className The class name.
285
     * @return Database
286
     */
287 1257
    public function getDocumentDatabase($className)
288
    {
289 1257
        $className = ltrim($className, '\\');
290
291 1257
        if (isset($this->documentDatabases[$className])) {
292 36
            return $this->documentDatabases[$className];
293
        }
294
295 1253
        $metadata = $this->metadataFactory->getMetadataFor($className);
296 1253
        assert($metadata instanceof ClassMetadata);
297 1253
        $db = $metadata->getDatabase();
298 1253
        $db = $db ?: $this->config->getDefaultDB();
299 1253
        $db = $db ?: 'doctrine';
300
        $this->documentDatabases[$className] = $this->client->selectDatabase($db);
301 1253
302
        return $this->documentDatabases[$className];
303
    }
304
305
    /**
306
     * Gets the array of instantiated document database instances.
307
     *
308
     * @return Database[]
309
     */
310
    public function getDocumentDatabases()
311
    {
312
        return $this->documentDatabases;
313
    }
314
315
    /**
316
     * Returns the MongoCollection instance for a class.
317
     *
318
     * @param string $className The class name.
319
     * @throws MongoDBException When the $className param is not mapped to a collection.
320
     * @return Collection
321 1259
     */
322
    public function getDocumentCollection($className)
323 1259
    {
324
        $className = ltrim($className, '\\');
325 1259
326 1259
        $metadata = $this->metadataFactory->getMetadataFor($className);
327
        assert($metadata instanceof ClassMetadata);
328 1259
        $collectionName = $metadata->getCollection();
329
330
        if (! $collectionName) {
331
            throw MongoDBException::documentNotMappedToCollection($className);
332 1259
        }
333 1249
334
        if (! isset($this->documentCollections[$className])) {
335 1249
            $db = $this->getDocumentDatabase($className);
336 1249
337 3
            $options = [];
338
            if ($metadata->readPreference !== null) {
339
                $options['readPreference'] = new ReadPreference($metadata->readPreference, $metadata->readPreferenceTags);
340 1249
            }
341
342
            $this->documentCollections[$className] = $db->selectCollection($collectionName, $options);
343 1259
        }
344
345
        return $this->documentCollections[$className];
346
    }
347
348
    /**
349
     * Gets the array of instantiated document collection instances.
350
     *
351
     * @return Collection[]
352
     */
353
    public function getDocumentCollections()
354
    {
355
        return $this->documentCollections;
356
    }
357
358
    /**
359
     * Create a new Query instance for a class.
360
     *
361
     * @param string $documentName The document class name.
362 180
     * @return Query\Builder
363
     */
364 180
    public function createQueryBuilder($documentName = null)
365
    {
366
        return new Query\Builder($this, $documentName);
367
    }
368
369
    /**
370
     * Creates a new aggregation builder instance for a class.
371
     *
372
     * @param string $documentName The document class name.
373 41
     * @return Aggregation\Builder
374
     */
375 41
    public function createAggregationBuilder($documentName)
376
    {
377
        return new Aggregation\Builder($this, $documentName);
378
    }
379
380
    /**
381
     * Tells the DocumentManager to make an instance managed and persistent.
382
     *
383
     * The document will be entered into the database at or before transaction
384
     * commit or as a result of the flush operation.
385
     *
386
     * NOTE: The persist operation always considers documents that are not yet known to
387
     * this DocumentManager as NEW. Do not pass detached documents to the persist operation.
388
     *
389
     * @param object $document The instance to make managed and persistent.
390 582
     * @throws \InvalidArgumentException When the given $document param is not an object.
391
     */
392 582
    public function persist($document)
393 1
    {
394
        if (! is_object($document)) {
395 581
            throw new \InvalidArgumentException(gettype($document));
396 580
        }
397 576
        $this->errorIfClosed();
398
        $this->unitOfWork->persist($document);
399
    }
400
401
    /**
402
     * Removes a document instance.
403
     *
404
     * A removed document will be removed from the database at or before transaction commit
405
     * or as a result of the flush operation.
406
     *
407
     * @param object $document The document instance to remove.
408 25
     * @throws \InvalidArgumentException When the $document param is not an object.
409
     */
410 25
    public function remove($document)
411 1
    {
412
        if (! is_object($document)) {
413 24
            throw new \InvalidArgumentException(gettype($document));
414 23
        }
415 23
        $this->errorIfClosed();
416
        $this->unitOfWork->remove($document);
417
    }
418
419
    /**
420
     * Refreshes the persistent state of a document from the database,
421
     * overriding any local changes that have not yet been persisted.
422
     *
423
     * @param object $document The document to refresh.
424 23
     * @throws \InvalidArgumentException When the given $document param is not an object.
425
     */
426 23
    public function refresh($document)
427 1
    {
428
        if (! is_object($document)) {
429 22
            throw new \InvalidArgumentException(gettype($document));
430 21
        }
431 20
        $this->errorIfClosed();
432
        $this->unitOfWork->refresh($document);
433
    }
434
435
    /**
436
     * Detaches a document from the DocumentManager, causing a managed document to
437
     * become detached.  Unflushed changes made to the document if any
438
     * (including removal of the document), will not be synchronized to the database.
439
     * Documents which previously referenced the detached document will continue to
440
     * reference it.
441
     *
442
     * @param object $document The document to detach.
443 11
     * @throws \InvalidArgumentException When the $document param is not an object.
444
     */
445 11
    public function detach($document)
446 1
    {
447
        if (! is_object($document)) {
448 10
            throw new \InvalidArgumentException(gettype($document));
449 10
        }
450
        $this->unitOfWork->detach($document);
451
    }
452
453
    /**
454
     * Merges the state of a detached document into the persistence context
455
     * of this DocumentManager and returns the managed copy of the document.
456
     * The document passed to merge will not become associated/managed with this DocumentManager.
457
     *
458
     * @param object $document The detached document to merge into the persistence context.
459
     * @throws LockException
460
     * @throws \InvalidArgumentException If the $document param is not an object.
461 14
     * @return object The managed copy of the document.
462
     */
463 14
    public function merge($document)
464 1
    {
465
        if (! is_object($document)) {
466 13
            throw new \InvalidArgumentException(gettype($document));
467 12
        }
468
        $this->errorIfClosed();
469
        return $this->unitOfWork->merge($document);
470
    }
471
472
    /**
473
     * Acquire a lock on the given document.
474
     *
475
     * @param object $document
476
     * @param int    $lockMode
477
     * @param int    $lockVersion
478 8
     * @throws \InvalidArgumentException
479
     */
480 8
    public function lock($document, $lockMode, $lockVersion = null)
481
    {
482
        if (! is_object($document)) {
483 8
            throw new \InvalidArgumentException(gettype($document));
484 5
        }
485
        $this->unitOfWork->lock($document, $lockMode, $lockVersion);
486
    }
487
488
    /**
489
     * Releases a lock on the given document.
490
     *
491
     * @param object $document
492 1
     * @throws \InvalidArgumentException If the $document param is not an object.
493
     */
494 1
    public function unlock($document)
495
    {
496
        if (! is_object($document)) {
497 1
            throw new \InvalidArgumentException(gettype($document));
498 1
        }
499
        $this->unitOfWork->unlock($document);
500
    }
501
502
    /**
503
     * Gets the repository for a document class.
504
     *
505
     * @param string $documentName The name of the Document.
506 328
     * @return ObjectRepository  The repository.
507
     */
508 328
    public function getRepository($documentName)
509
    {
510
        return $this->repositoryFactory->getRepository($this, $documentName);
511
    }
512
513
    /**
514
     * Flushes all changes to objects that have been queued up to now to the database.
515
     * This effectively synchronizes the in-memory state of managed objects with the
516
     * database.
517
     *
518
     * @param array $options Array of options to be used with batchInsert(), update() and remove()
519 553
     * @throws \InvalidArgumentException
520
     */
521 553
    public function flush(array $options = [])
522 552
    {
523 549
        $this->errorIfClosed();
524
        $this->unitOfWork->commit($options);
525
    }
526
527
    /**
528
     * Gets a reference to the document identified by the given type and identifier
529
     * without actually loading it.
530
     *
531
     * If partial objects are allowed, this method will return a partial object that only
532
     * has its identifier populated. Otherwise a proxy is returned that automatically
533
     * loads itself on first access.
534
     *
535
     * @param string        $documentName
536
     * @param string|object $identifier
537 126
     * @return mixed|object The document reference.
538
     */
539
    public function getReference($documentName, $identifier)
540 126
    {
541 126
        /** @var ClassMetadata $class */
542
        $class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
543
        $document = $this->unitOfWork->tryGetById($identifier, $class);
544 126
545 56
        // Check identity map first, if its already in there just return it.
546
        if ($document) {
547
            return $document;
548 97
        }
549 97
550
        $document = $this->proxyFactory->getProxy($class->name, [$class->identifier => $identifier]);
551 97
        $this->unitOfWork->registerManaged($document, $identifier, []);
552
553
        return $document;
554
    }
555
556
    /**
557
     * Gets a partial reference to the document identified by the given type and identifier
558
     * without actually loading it, if the document is not yet loaded.
559
     *
560
     * The returned reference may be a partial object if the document is not yet loaded/managed.
561
     * If it is a partial object it will not initialize the rest of the document state on access.
562
     * Thus you can only ever safely access the identifier of a document obtained through
563
     * this method.
564
     *
565
     * The use-cases for partial references involve maintaining bidirectional associations
566
     * without loading one side of the association or to update a document without loading it.
567
     * Note, however, that in the latter case the original (persistent) document data will
568
     * never be visible to the application (especially not event listeners) as it will
569
     * never be loaded in the first place.
570
     *
571
     * @param string $documentName The name of the document type.
572
     * @param mixed  $identifier   The document identifier.
573 1
     * @return object The (partial) document reference.
574
     */
575 1
    public function getPartialReference($documentName, $identifier)
576 1
    {
577
        $class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
578
        assert($class instanceof ClassMetadata);
579 1
        $document = $this->unitOfWork->tryGetById($identifier, $class);
580
581
        // Check identity map first, if its already in there just return it.
582 1
        if ($document) {
583 1
            return $document;
584 1
        }
585
        $document = $class->newInstance();
586 1
        $class->setIdentifierValue($document, $identifier);
587
        $this->unitOfWork->registerManaged($document, $identifier, []);
588
589
        return $document;
590
    }
591
592
    /**
593
     * Finds a Document by its identifier.
594
     *
595
     * This is just a convenient shortcut for getRepository($documentName)->find($id).
596
     *
597
     * @param string $documentName
598
     * @param mixed  $identifier
599
     * @param int    $lockMode
600 182
     * @param int    $lockVersion
601
     * @return object $document
602 182
     */
603
    public function find($documentName, $identifier, $lockMode = LockMode::NONE, $lockVersion = null)
604
    {
605
        $repository = $this->getRepository($documentName);
606
        if ($repository instanceof DocumentRepository) {
607
            return $repository->find($identifier, $lockMode, $lockVersion);
608
        }
609
610
        return $repository->find($identifier);
611
    }
612
613 371
    /**
614
     * Clears the DocumentManager.
615 371
     *
616 371
     * All documents that are currently managed by this DocumentManager become
617
     * detached.
618
     *
619
     * @param string|null $documentName if given, only documents of this type will get detached
620
     */
621
    public function clear($documentName = null)
622
    {
623 6
        $this->unitOfWork->clear($documentName);
624
    }
625 6
626 6
    /**
627 6
     * Closes the DocumentManager. All documents that are currently managed
628
     * by this DocumentManager become detached. The DocumentManager may no longer
629
     * be used after it is closed.
630
     */
631
    public function close()
632
    {
633
        $this->clear();
634
        $this->closed = true;
635
    }
636 3
637
    /**
638 3
     * Determines whether a document instance is managed in this DocumentManager.
639
     *
640
     * @param object $document
641 3
     * @throws \InvalidArgumentException When the $document param is not an object.
642 3
     * @return bool TRUE if this DocumentManager currently manages the given document, FALSE otherwise.
643 3
     */
644
    public function contains($document)
645
    {
646
        if (! is_object($document)) {
647
            throw new \InvalidArgumentException(gettype($document));
648
        }
649
        return $this->unitOfWork->isScheduledForInsert($document) ||
650
            $this->unitOfWork->isInIdentityMap($document) &&
651 721
            ! $this->unitOfWork->isScheduledForDelete($document);
652
    }
653 721
654
    /**
655
     * Gets the Configuration used by the DocumentManager.
656
     *
657
     * @return Configuration
658
     */
659
    public function getConfiguration()
660
    {
661
        return $this->config;
662
    }
663
664
    /**
665
     * Returns a reference to the supplied document.
666 224
     *
667
     * @param object $document         A document object
668 224
     * @param array  $referenceMapping Mapping for the field that references the document
669
     *
670
     * @throws \InvalidArgumentException
671
     * @throws MappingException
672 224
     * @return mixed The reference for the document in question, according to the desired mapping
673 224
     */
674
    public function createReference($document, array $referenceMapping)
675 224
    {
676 1
        if (! is_object($document)) {
677 1
            throw new \InvalidArgumentException('Cannot create a DBRef, the document is not an object');
678
        }
679
680
        $class = $this->getClassMetadata(get_class($document));
681 223
        $id = $this->unitOfWork->getDocumentIdentifier($document);
682 223
683 223
        if ($id === null) {
684
            throw new \RuntimeException(
685 46
                sprintf('Cannot create a DBRef for class %s without an identifier. Have you forgotten to persist/merge the document first?', $class->name)
686 1
            );
687
        }
688
689 45
        $storeAs = $referenceMapping['storeAs'] ?? null;
690
        $reference = [];
0 ignored issues
show
Unused Code introduced by
$reference is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
691
        switch ($storeAs) {
692
            case ClassMetadata::REFERENCE_STORE_AS_ID:
693 20
                if ($class->inheritanceType === ClassMetadata::INHERITANCE_TYPE_SINGLE_COLLECTION) {
694 20
                    throw MappingException::simpleReferenceMustNotTargetDiscriminatedDocument($referenceMapping['targetDocument']);
695
                }
696
697
                return $class->getDatabaseIdentifierValue($id);
698 179
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
699 179
700
            case ClassMetadata::REFERENCE_STORE_AS_REF:
701 179
                $reference = ['id' => $class->getDatabaseIdentifierValue($id)];
702
                break;
703
704
            case ClassMetadata::REFERENCE_STORE_AS_DB_REF:
705 17
                $reference = [
706 17
                    '$ref' => $class->getCollection(),
707 17
                    '$id'  => $class->getDatabaseIdentifierValue($id),
708
                ];
709 17
                break;
710
711
            case ClassMetadata::REFERENCE_STORE_AS_DB_REF_WITH_DB:
712
                $reference = [
713
                    '$ref' => $class->getCollection(),
714
                    '$id'  => $class->getDatabaseIdentifierValue($id),
715
                    '$db'  => $this->getDocumentDatabase($class->name)->getDatabaseName(),
716
                ];
717
                break;
718
719 201
            default:
720 18
                throw new \InvalidArgumentException(sprintf('Reference type %s is invalid.', $storeAs));
721
        }
722
723
        /* If the class has a discriminator (field and value), use it. A child
724
         * class that is not defined in the discriminator map may only have a
725
         * discriminator field and no value, so default to the full class name.
726 201
         */
727 33
        if (isset($class->discriminatorField)) {
728 33
            $reference[$class->discriminatorField] = $class->discriminatorValue ?? $class->name;
729 8
        }
730 33
731
        /* Add a discriminator value if the referenced document is not mapped
732
         * explicitly to a targetDocument class.
733
         */
734
        if (! isset($referenceMapping['targetDocument'])) {
735
            $discriminatorField = $referenceMapping['discriminatorField'];
736
            $discriminatorValue = isset($referenceMapping['discriminatorMap'])
737
                ? array_search($class->name, $referenceMapping['discriminatorMap'])
738 33
                : $class->name;
739 2
740
            /* If the discriminator value was not found in the map, use the full
741
             * class name. In the future, it may be preferable to throw an
742 33
             * exception here (perhaps based on some strictness option).
743
             *
744
             * @see PersistenceBuilder::prepareEmbeddedDocumentValue()
745 201
             */
746
            if ($discriminatorValue === false) {
747
                $discriminatorValue = $class->name;
748
            }
749
750
            $reference[$discriminatorField] = $discriminatorValue;
751
        }
752
753 586
        return $reference;
754
    }
755 586
756 5
    /**
757
     * Throws an exception if the DocumentManager is closed or currently not active.
758 581
     *
759
     * @throws MongoDBException If the DocumentManager is closed.
760
     */
761
    private function errorIfClosed()
762
    {
763
        if ($this->closed) {
764
            throw MongoDBException::documentManagerClosed();
765 1
        }
766
    }
767 1
768
    /**
769
     * Check if the Document manager is open or closed.
770
     *
771
     * @return bool
772
     */
773
    public function isOpen()
774
    {
775 507
        return ! $this->closed;
776
    }
777 507
778 507
    /**
779
     * Gets the filter collection.
780
     *
781 507
     * @return FilterCollection The active filter collection.
782
     */
783
    public function getFilterCollection()
784
    {
785
        if ($this->filterCollection === null) {
786
            $this->filterCollection = new FilterCollection($this);
787
        }
788
789
        return $this->filterCollection;
790
    }
791
}
792