Completed
Pull Request — master (#1875)
by Andreas
61:52
created

DocumentManager::getClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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\ClassNameResolver;
15
use Doctrine\ODM\MongoDB\Proxy\Factory\ProxyFactory;
16
use Doctrine\ODM\MongoDB\Proxy\Factory\StaticProxyFactory;
17
use Doctrine\ODM\MongoDB\Query\FilterCollection;
18
use Doctrine\ODM\MongoDB\Repository\RepositoryFactory;
19
use InvalidArgumentException;
20
use MongoDB\Client;
21
use MongoDB\Collection;
22
use MongoDB\Database;
23
use MongoDB\Driver\ReadPreference;
24
use MongoDB\GridFS\Bucket;
25
use RuntimeException;
26
use function array_search;
27
use function get_class;
28
use function gettype;
29
use function is_object;
30
use function ltrim;
31
use function sprintf;
32
33
/**
34
 * The DocumentManager class is the central access point for managing the
35
 * persistence of documents.
36
 *
37
 *     <?php
38
 *
39
 *     $config = new Configuration();
40
 *     $dm = DocumentManager::create(new Connection(), $config);
41
 */
42
class DocumentManager implements ObjectManager
43
{
44
    public const CLIENT_TYPEMAP = ['root' => 'array', 'document' => 'array'];
45
46
    /**
47
     * The Doctrine MongoDB connection instance.
48
     *
49
     * @var Client
50
     */
51
    private $client;
52
53
    /**
54
     * The used Configuration.
55
     *
56
     * @var Configuration
57
     */
58
    private $config;
59
60
    /**
61
     * The metadata factory, used to retrieve the ODM metadata of document classes.
62
     *
63
     * @var ClassMetadataFactory
64
     */
65
    private $metadataFactory;
66
67
    /**
68
     * The UnitOfWork used to coordinate object-level transactions.
69
     *
70
     * @var UnitOfWork
71
     */
72
    private $unitOfWork;
73
74
    /**
75
     * The event manager that is the central point of the event system.
76
     *
77
     * @var EventManager
78
     */
79
    private $eventManager;
80
81
    /**
82
     * The Hydrator factory instance.
83
     *
84
     * @var HydratorFactory
85
     */
86
    private $hydratorFactory;
87
88
    /**
89
     * The Proxy factory instance.
90
     *
91
     * @var ProxyFactory
92
     */
93
    private $proxyFactory;
94
95
    /**
96
     * The repository factory used to create dynamic repositories.
97
     *
98
     * @var RepositoryFactory
99
     */
100
    private $repositoryFactory;
101
102
    /**
103
     * SchemaManager instance
104
     *
105
     * @var SchemaManager
106
     */
107
    private $schemaManager;
108
109
    /**
110
     * Array of cached document database instances that are lazily loaded.
111
     *
112
     * @var Database[]
113
     */
114
    private $documentDatabases = [];
115
116
    /**
117
     * Array of cached document collection instances that are lazily loaded.
118
     *
119
     * @var Collection[]
120
     */
121
    private $documentCollections = [];
122
123
    /**
124
     * Array of cached document bucket instances that are lazily loaded.
125
     *
126
     * @var Bucket[]
127
     */
128
    private $documentBuckets = [];
129
130
    /**
131
     * Whether the DocumentManager is closed or not.
132
     *
133
     * @var bool
134
     */
135
    private $closed = false;
136
137
    /**
138
     * Collection of query filters.
139
     *
140
     * @var FilterCollection
141
     */
142
    private $filterCollection;
143
144
    /** @var ClassNameResolver */
145
    private $classNameResolver;
146 1636
147
    /**
148 1636
     * Creates a new Document that operates on the given Mongo connection
149 1636
     * and uses the given Configuration.
150 1636
     */
151
    protected function __construct(?Client $client = null, ?Configuration $config = null, ?EventManager $eventManager = null)
152 1636
    {
153
        $this->config       = $config ?: new Configuration();
154 1636
        $this->eventManager = $eventManager ?: new EventManager();
155 1636
        $this->client       = $client ?: new Client('mongodb://127.0.0.1', [], ['typeMap' => self::CLIENT_TYPEMAP]);
156 1636
157 1636
        $this->checkTypeMap();
158
159 1636
        $metadataFactoryClassName = $this->config->getClassMetadataFactoryName();
160 1636
        $this->metadataFactory    = new $metadataFactoryClassName();
161
        $this->metadataFactory->setDocumentManager($this);
162
        $this->metadataFactory->setConfiguration($this->config);
163
164 1636
        $cacheDriver = $this->config->getMetadataCacheImpl();
165 1636
        if ($cacheDriver) {
166 1636
            $this->metadataFactory->setCacheDriver($cacheDriver);
167 1636
        }
168 1636
169 1636
        $hydratorDir           = $this->config->getHydratorDir();
170 1636
        $hydratorNs            = $this->config->getHydratorNamespace();
171 1636
        $this->hydratorFactory = new HydratorFactory(
172
            $this,
173
            $this->eventManager,
174 1636
            $hydratorDir,
175 1636
            $hydratorNs,
176 1636
            $this->config->getAutoGenerateHydratorClasses()
177 1636
        );
178 1636
179 1636
        $this->unitOfWork = new UnitOfWork($this, $this->eventManager, $this->hydratorFactory);
180 1636
        $this->hydratorFactory->setUnitOfWork($this->unitOfWork);
181 1636
        $this->schemaManager     = new SchemaManager($this, $this->metadataFactory);
182
        $this->proxyFactory      = new StaticProxyFactory($this);
183 1636
        $this->repositoryFactory = $this->config->getRepositoryFactory();
184 1636
        $this->classNameResolver = new ClassNameResolver($this->config);
185
    }
186
187
    /**
188
     * Gets the proxy factory used by the DocumentManager to create document proxies.
189 1
     */
190
    public function getProxyFactory() : ProxyFactory
191 1
    {
192
        return $this->proxyFactory;
193
    }
194
195
    /**
196
     * Creates a new Document that operates on the given Mongo connection
197
     * and uses the given Configuration.
198 1636
     */
199
    public static function create(?Client $client = null, ?Configuration $config = null, ?EventManager $eventManager = null) : DocumentManager
200 1636
    {
201
        return new static($client, $config, $eventManager);
202
    }
203
204
    /**
205
     * Gets the EventManager used by the DocumentManager.
206 1699
     */
207
    public function getEventManager() : EventManager
208 1699
    {
209
        return $this->eventManager;
210
    }
211
212
    /**
213
     * Gets the MongoDB client instance that this DocumentManager wraps.
214 1636
     */
215
    public function getClient() : Client
216 1636
    {
217
        return $this->client;
218
    }
219
220
    /**
221
     * Gets the metadata factory used to gather the metadata of classes.
222
     *
223
     * @return ClassMetadataFactory
224 1636
     */
225
    public function getMetadataFactory()
226 1636
    {
227
        return $this->metadataFactory;
228
    }
229
230
    /**
231
     * Helper method to initialize a lazy loading proxy or persistent collection.
232
     *
233
     * This method is a no-op for other objects.
234
     *
235
     * @param object $obj
236
     */
237
    public function initializeObject($obj)
238
    {
239
        $this->unitOfWork->initializeObject($obj);
240
    }
241
242
    /**
243
     * Gets the UnitOfWork used by the DocumentManager to coordinate operations.
244 1643
     */
245
    public function getUnitOfWork() : UnitOfWork
246 1643
    {
247
        return $this->unitOfWork;
248
    }
249
250
    /**
251
     * Gets the Hydrator factory used by the DocumentManager to generate and get hydrators
252
     * for each type of document.
253 70
     */
254
    public function getHydratorFactory() : HydratorFactory
255 70
    {
256
        return $this->hydratorFactory;
257
    }
258
259
    /**
260
     * Returns SchemaManager, used to create/drop indexes/collections/databases.
261 28
     */
262
    public function getSchemaManager() : SchemaManager
263 28
    {
264
        return $this->schemaManager;
265
    }
266
267
    /** Returns the class name resolver which is used to resolve real class names for proxy objects. */
268
    public function getClassNameResolver() : ClassNameResolver
269
    {
270
        return $this->classNameResolver;
271
    }
272
273
    /**
274
     * Returns the metadata for a class.
275 1371
     *
276
     * @internal Performance-sensitive method.
277 1371
     *
278
     * @param string $className The class name.
279
     */
280
    public function getClassMetadata($className) : ClassMetadata
281
    {
282
        return $this->metadataFactory->getMetadataFor($className);
283 1300
    }
284
285 1300
    /**
286
     * Returns the MongoDB instance for a class.
287 1300
     */
288 46
    public function getDocumentDatabase(string $className) : Database
289
    {
290
        $className = $this->classNameResolver->getRealClass($className);
291 1295
292 1295
        if (isset($this->documentDatabases[$className])) {
293 1295
            return $this->documentDatabases[$className];
294 1295
        }
295 1295
296
        $metadata                            = $this->metadataFactory->getMetadataFor($className);
297 1295
        $db                                  = $metadata->getDatabase();
298
        $db                                  = $db ?: $this->config->getDefaultDB();
299
        $db                                  = $db ?: 'doctrine';
300
        $this->documentDatabases[$className] = $this->client->selectDatabase($db);
301
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() : array
311
    {
312
        return $this->documentDatabases;
313
    }
314
315 1303
    /**
316
     * Returns the collection instance for a class.
317 1303
     *
318
     * @throws MongoDBException When the $className param is not mapped to a collection.
319
     */
320 1303
    public function getDocumentCollection(string $className) : Collection
321 1303
    {
322 16
        $className = $this->classNameResolver->getRealClass($className);
323
324
        /** @var ClassMetadata $metadata */
325 1292
        $metadata = $this->metadataFactory->getMetadataFor($className);
326
        if ($metadata->isFile) {
327 1292
            return $this->getDocumentBucket($className)->getFilesCollection();
328
        }
329
330
        $collectionName = $metadata->getCollection();
331 1292
332 1282
        if (! $collectionName) {
333
            throw MongoDBException::documentNotMappedToCollection($className);
334 1282
        }
335 1282
336 3
        if (! isset($this->documentCollections[$className])) {
337
            $db = $this->getDocumentDatabase($className);
338
339 1282
            $options = [];
340
            if ($metadata->readPreference !== null) {
341
                $options['readPreference'] = new ReadPreference($metadata->readPreference, $metadata->readPreferenceTags);
342 1292
            }
343
344
            $this->documentCollections[$className] = $db->selectCollection($collectionName, $options);
345
        }
346
347
        return $this->documentCollections[$className];
348
    }
349
350 16
    /**
351
     * Returns the bucket instance for a class.
352 16
     *
353
     * @throws MongoDBException When the $className param is not mapped to a collection.
354
     */
355 16
    public function getDocumentBucket(string $className) : Bucket
356 16
    {
357
        $className = $this->classNameResolver->getRealClass($className);
358
359
        /** @var ClassMetadata $metadata */
360 16
        $metadata = $this->metadataFactory->getMetadataFor($className);
361
        if (! $metadata->isFile) {
362 16
            throw MongoDBException::documentBucketOnlyAvailableForGridFSFiles($className);
363
        }
364
365
        $bucketName = $metadata->getBucketName();
366 16
367 11
        if (! $bucketName) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $bucketName of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
368
            throw MongoDBException::documentNotMappedToCollection($className);
369 11
        }
370 11
371
        if (! isset($this->documentBuckets[$className])) {
372
            $db = $this->getDocumentDatabase($className);
373
374 11
            $options = ['bucketName' => $bucketName];
375
            if ($metadata->readPreference !== null) {
376
                $options['readPreference'] = new ReadPreference($metadata->readPreference, $metadata->readPreferenceTags);
377 16
            }
378
379
            $this->documentBuckets[$className] = $db->selectGridFSBucket($options);
380
        }
381
382
        return $this->documentBuckets[$className];
383
    }
384
385
    /**
386
     * Gets the array of instantiated document collection instances.
387
     *
388
     * @return Collection[]
389
     */
390
    public function getDocumentCollections() : array
391
    {
392
        return $this->documentCollections;
393
    }
394
395 182
    /**
396
     * Create a new Query instance for a class.
397 182
     *
398
     * @param string[]|string|null $documentName (optional) an array of document names, the document name, or none
399
     */
400
    public function createQueryBuilder($documentName = null) : Query\Builder
401
    {
402
        return new Query\Builder($this, $documentName);
403 41
    }
404
405 41
    /**
406
     * Creates a new aggregation builder instance for a class.
407
     */
408
    public function createAggregationBuilder(string $documentName) : Aggregation\Builder
409
    {
410
        return new Aggregation\Builder($this, $documentName);
411
    }
412
413
    /**
414
     * Tells the DocumentManager to make an instance managed and persistent.
415
     *
416
     * The document will be entered into the database at or before transaction
417
     * commit or as a result of the flush operation.
418
     *
419
     * NOTE: The persist operation always considers documents that are not yet known to
420
     * this DocumentManager as NEW. Do not pass detached documents to the persist operation.
421 615
     *
422
     * @param object $document The instance to make managed and persistent.
423 615
     *
424 1
     * @throws InvalidArgumentException When the given $document param is not an object.
425
     */
426 614
    public function persist($document)
427 613
    {
428 609
        if (! is_object($document)) {
429
            throw new InvalidArgumentException(gettype($document));
430
        }
431
        $this->errorIfClosed();
432
        $this->unitOfWork->persist($document);
433
    }
434
435
    /**
436
     * Removes a document instance.
437
     *
438
     * A removed document will be removed from the database at or before transaction commit
439
     * or as a result of the flush operation.
440 27
     *
441
     * @param object $document The document instance to remove.
442 27
     *
443 1
     * @throws InvalidArgumentException When the $document param is not an object.
444
     */
445 26
    public function remove($document)
446 25
    {
447 25
        if (! is_object($document)) {
448
            throw new InvalidArgumentException(gettype($document));
449
        }
450
        $this->errorIfClosed();
451
        $this->unitOfWork->remove($document);
452
    }
453
454
    /**
455
     * Refreshes the persistent state of a document from the database,
456
     * overriding any local changes that have not yet been persisted.
457 26
     *
458
     * @param object $document The document to refresh.
459 26
     *
460 1
     * @throws InvalidArgumentException When the given $document param is not an object.
461
     */
462 25
    public function refresh($document)
463 24
    {
464 23
        if (! is_object($document)) {
465
            throw new InvalidArgumentException(gettype($document));
466
        }
467
        $this->errorIfClosed();
468
        $this->unitOfWork->refresh($document);
469
    }
470
471
    /**
472
     * Detaches a document from the DocumentManager, causing a managed document to
473
     * become detached.  Unflushed changes made to the document if any
474
     * (including removal of the document), will not be synchronized to the database.
475
     * Documents which previously referenced the detached document will continue to
476
     * reference it.
477 11
     *
478
     * @param object $document The document to detach.
479 11
     *
480 1
     * @throws InvalidArgumentException When the $document param is not an object.
481
     */
482 10
    public function detach($document)
483 10
    {
484
        if (! is_object($document)) {
485
            throw new InvalidArgumentException(gettype($document));
486
        }
487
        $this->unitOfWork->detach($document);
488
    }
489
490
    /**
491
     * Merges the state of a detached document into the persistence context
492
     * of this DocumentManager and returns the managed copy of the document.
493
     * The document passed to merge will not become associated/managed with this DocumentManager.
494
     *
495
     * @param object $document The detached document to merge into the persistence context.
496
     *
497 14
     * @return object The managed copy of the document.
498
     *
499 14
     * @throws LockException
500 1
     * @throws InvalidArgumentException If the $document param is not an object.
501
     */
502 13
    public function merge($document)
503 12
    {
504
        if (! is_object($document)) {
505
            throw new InvalidArgumentException(gettype($document));
506
        }
507
        $this->errorIfClosed();
508
        return $this->unitOfWork->merge($document);
509
    }
510
511
    /**
512 8
     * Acquire a lock on the given document.
513
     *
514 8
     * @throws InvalidArgumentException
515 5
     * @throws LockException
516
     */
517
    public function lock(object $document, int $lockMode, ?int $lockVersion = null) : void
518
    {
519
        $this->unitOfWork->lock($document, $lockMode, $lockVersion);
520 1
    }
521
522 1
    /**
523 1
     * Releases a lock on the given document.
524
     */
525
    public function unlock(object $document) : void
526
    {
527
        $this->unitOfWork->unlock($document);
528
    }
529
530
    /**
531
     * Gets the repository for a document class.
532 358
     *
533
     * @param string $documentName The name of the Document.
534 358
     *
535
     * @return ObjectRepository  The repository.
536
     */
537
    public function getRepository($documentName)
538
    {
539
        return $this->repositoryFactory->getRepository($this, $documentName);
540
    }
541
542
    /**
543
     * Flushes all changes to objects that have been queued up to now to the database.
544
     * This effectively synchronizes the in-memory state of managed objects with the
545
     * database.
546 587
     *
547
     * @param array $options Array of options to be used with batchInsert(), update() and remove()
548 587
     *
549 586
     * @throws MongoDBException
550 583
     */
551
    public function flush(array $options = [])
552
    {
553
        $this->errorIfClosed();
554
        $this->unitOfWork->commit($options);
555
    }
556
557
    /**
558
     * Gets a reference to the document identified by the given type and identifier
559
     * without actually loading it.
560
     *
561
     * If partial objects are allowed, this method will return a partial object that only
562 134
     * has its identifier populated. Otherwise a proxy is returned that automatically
563
     * loads itself on first access.
564
     *
565 134
     * @param string|object $identifier
566 134
     */
567
    public function getReference(string $documentName, $identifier) : object
568
    {
569 134
        /** @var ClassMetadata $class */
570 56
        $class    = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
571
        $document = $this->unitOfWork->tryGetById($identifier, $class);
572
573 105
        // Check identity map first, if its already in there just return it.
574 105
        if ($document) {
575
            return $document;
576 105
        }
577
578
        $document = $this->proxyFactory->getProxy($class, $identifier);
579
        $this->unitOfWork->registerManaged($document, $identifier, []);
580
581
        return $document;
582
    }
583
584
    /**
585
     * Gets a partial reference to the document identified by the given type and identifier
586
     * without actually loading it, if the document is not yet loaded.
587
     *
588
     * The returned reference may be a partial object if the document is not yet loaded/managed.
589
     * If it is a partial object it will not initialize the rest of the document state on access.
590
     * Thus you can only ever safely access the identifier of a document obtained through
591
     * this method.
592
     *
593
     * The use-cases for partial references involve maintaining bidirectional associations
594
     * without loading one side of the association or to update a document without loading it.
595
     * Note, however, that in the latter case the original (persistent) document data will
596 1
     * never be visible to the application (especially not event listeners) as it will
597
     * never be loaded in the first place.
598 1
     *
599 1
     * @param mixed $identifier The document identifier.
600
     */
601
    public function getPartialReference(string $documentName, $identifier) : object
602 1
    {
603
        $class    = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
604
        $document = $this->unitOfWork->tryGetById($identifier, $class);
605 1
606 1
        // Check identity map first, if its already in there just return it.
607 1
        if ($document) {
608
            return $document;
609 1
        }
610
        $document = $class->newInstance();
611
        $class->setIdentifierValue($document, $identifier);
612
        $this->unitOfWork->registerManaged($document, $identifier, []);
613
614
        return $document;
615
    }
616
617
    /**
618
     * Finds a Document by its identifier.
619
     *
620
     * This is just a convenient shortcut for getRepository($documentName)->find($id).
621
     *
622
     * @param string $documentName
623
     * @param mixed  $identifier
624 187
     * @param int    $lockMode
625
     * @param int    $lockVersion
626 187
     *
627
     * @return object $document
628
     */
629
    public function find($documentName, $identifier, $lockMode = LockMode::NONE, $lockVersion = null)
630
    {
631
        return $this->getRepository($documentName)->find($identifier, $lockMode, $lockVersion);
632
    }
633
634
    /**
635
     * Clears the DocumentManager.
636
     *
637 390
     * All documents that are currently managed by this DocumentManager become
638
     * detached.
639 390
     *
640 390
     * @param string|null $documentName if given, only documents of this type will get detached
641
     */
642
    public function clear($documentName = null)
643
    {
644
        $this->unitOfWork->clear($documentName);
645
    }
646
647 6
    /**
648
     * Closes the DocumentManager. All documents that are currently managed
649 6
     * by this DocumentManager become detached. The DocumentManager may no longer
650 6
     * be used after it is closed.
651 6
     */
652
    public function close()
653
    {
654
        $this->clear();
655
        $this->closed = true;
656
    }
657
658
    /**
659
     * Determines whether a document instance is managed in this DocumentManager.
660
     *
661
     * @param object $document
662 3
     *
663
     * @return bool TRUE if this DocumentManager currently manages the given document, FALSE otherwise.
664 3
     *
665
     * @throws InvalidArgumentException When the $document param is not an object.
666
     */
667 3
    public function contains($document)
668 3
    {
669 3
        if (! is_object($document)) {
670
            throw new InvalidArgumentException(gettype($document));
671
        }
672
        return $this->unitOfWork->isScheduledForInsert($document) ||
673
            $this->unitOfWork->isInIdentityMap($document) &&
674
            ! $this->unitOfWork->isScheduledForDelete($document);
675 783
    }
676
677 783
    /**
678
     * Gets the Configuration used by the DocumentManager.
679
     */
680
    public function getConfiguration() : Configuration
681
    {
682
        return $this->config;
683
    }
684
685
    /**
686
     * Returns a reference to the supplied document.
687
     *
688 226
     * @return mixed The reference for the document in question, according to the desired mapping
689
     *
690 226
     * @throws MappingException
691 226
     * @throws RuntimeException
692
     */
693 226
    public function createReference(object $document, array $referenceMapping)
694 1
    {
695 1
        $class = $this->getClassMetadata(get_class($document));
696
        $id    = $this->unitOfWork->getDocumentIdentifier($document);
697
698
        if ($id === null) {
699 225
            throw new RuntimeException(
700 225
                sprintf('Cannot create a DBRef for class %s without an identifier. Have you forgotten to persist/merge the document first?', $class->name)
701 225
            );
702
        }
703 46
704 1
        $storeAs   = $referenceMapping['storeAs'] ?? null;
705
        $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...
706
        switch ($storeAs) {
707 45
            case ClassMetadata::REFERENCE_STORE_AS_ID:
708
                if ($class->inheritanceType === ClassMetadata::INHERITANCE_TYPE_SINGLE_COLLECTION) {
709
                    throw MappingException::simpleReferenceMustNotTargetDiscriminatedDocument($referenceMapping['targetDocument']);
710
                }
711 20
712 20
                return $class->getDatabaseIdentifierValue($id);
713
                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...
714
715
            case ClassMetadata::REFERENCE_STORE_AS_REF:
716 181
                $reference = ['id' => $class->getDatabaseIdentifierValue($id)];
717 181
                break;
718
719 181
            case ClassMetadata::REFERENCE_STORE_AS_DB_REF:
720
                $reference = [
721
                    '$ref' => $class->getCollection(),
722
                    '$id'  => $class->getDatabaseIdentifierValue($id),
723 17
                ];
724 17
                break;
725 17
726
            case ClassMetadata::REFERENCE_STORE_AS_DB_REF_WITH_DB:
727 17
                $reference = [
728
                    '$ref' => $class->getCollection(),
729
                    '$id'  => $class->getDatabaseIdentifierValue($id),
730
                    '$db'  => $this->getDocumentDatabase($class->name)->getDatabaseName(),
731
                ];
732
                break;
733
734
            default:
735
                throw new InvalidArgumentException(sprintf('Reference type %s is invalid.', $storeAs));
736
        }
737 203
738 18
        /* If the class has a discriminator (field and value), use it. A child
739
         * class that is not defined in the discriminator map may only have a
740
         * discriminator field and no value, so default to the full class name.
741
         */
742
        if (isset($class->discriminatorField)) {
743
            $reference[$class->discriminatorField] = $class->discriminatorValue ?? $class->name;
744 203
        }
745 33
746 33
        /* Add a discriminator value if the referenced document is not mapped
747 8
         * explicitly to a targetDocument class.
748 33
         */
749
        if (! isset($referenceMapping['targetDocument'])) {
750
            $discriminatorField = $referenceMapping['discriminatorField'];
751
            $discriminatorValue = isset($referenceMapping['discriminatorMap'])
752
                ? array_search($class->name, $referenceMapping['discriminatorMap'])
753
                : $class->name;
754
755
            /* If the discriminator value was not found in the map, use the full
756 33
             * class name. In the future, it may be preferable to throw an
757 3
             * exception here (perhaps based on some strictness option).
758
             *
759
             * @see PersistenceBuilder::prepareEmbeddedDocumentValue()
760 33
             */
761
            if ($discriminatorValue === false) {
762
                $discriminatorValue = $class->name;
763 203
            }
764
765
            $reference[$discriminatorField] = $discriminatorValue;
766
        }
767
768
        return $reference;
769
    }
770
771 620
    /**
772
     * Throws an exception if the DocumentManager is closed or currently not active.
773 620
     *
774 5
     * @throws MongoDBException If the DocumentManager is closed.
775
     */
776 615
    private function errorIfClosed() : void
777
    {
778
        if ($this->closed) {
779
            throw MongoDBException::documentManagerClosed();
780
        }
781 1
    }
782
783 1
    /**
784
     * Check if the Document manager is open or closed.
785
     */
786
    public function isOpen() : bool
787
    {
788
        return ! $this->closed;
789 537
    }
790
791 537
    /**
792 537
     * Gets the filter collection.
793
     */
794
    public function getFilterCollection() : FilterCollection
795 537
    {
796
        if ($this->filterCollection === null) {
797
            $this->filterCollection = new FilterCollection($this);
798 1636
        }
799
800 1636
        return $this->filterCollection;
801
    }
802 1636
803 1636
    private function checkTypeMap() : void
804 1636
    {
805
        $typeMap = $this->client->getTypeMap();
806
807 1636
        foreach (self::CLIENT_TYPEMAP as $part => $expectedType) {
808
            if (! isset($typeMap[$part]) || $typeMap[$part] !== $expectedType) {
809
                throw MongoDBException::invalidTypeMap($part, $expectedType);
810
            }
811
        }
812
    }
813
}
814