Completed
Pull Request — master (#1790)
by Andreas
20:58
created

DocumentManager::getProxyFactory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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