DocumentManager   F
last analyzed

Complexity

Total Complexity 85

Size/Duplication

Total Lines 797
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 16

Test Coverage

Coverage 93.28%

Importance

Changes 0
Metric Value
wmc 85
lcom 3
cbo 16
dl 0
loc 797
ccs 222
cts 238
cp 0.9328
rs 1.803
c 0
b 0
f 0

41 Methods

Rating   Name   Duplication   Size   Complexity  
A getClient() 0 4 1
A getMetadataFactory() 0 4 1
A initializeObject() 0 4 1
A getClassMetadata() 0 4 1
A getDocumentDatabase() 0 18 4
A getDocumentDatabases() 0 4 1
A getDocumentCollection() 0 30 5
A getDocumentBucket() 0 29 5
A getDocumentCollections() 0 4 1
A createQueryBuilder() 0 4 1
A createAggregationBuilder() 0 4 1
A persist() 0 8 2
A remove() 0 8 2
A refresh() 0 8 2
A detach() 0 7 2
A getConfiguration() 0 4 1
A merge() 0 9 2
A lock() 0 4 1
A unlock() 0 4 1
A getRepository() 0 4 1
A flush() 0 5 1
A getReference() 0 16 2
A getPartialReference() 0 16 2
A find() 0 9 2
A clear() 0 4 1
A close() 0 5 1
A contains() 0 10 4
B createReference() 0 44 7
B getDiscriminatorData() 0 40 8
A errorIfClosed() 0 6 2
A isOpen() 0 4 1
A getFilterCollection() 0 8 2
A checkTypeMap() 0 10 4
A getEventManager() 0 4 1
A __construct() 0 35 5
A getProxyFactory() 0 4 1
A create() 0 4 1
A getUnitOfWork() 0 4 1
A getHydratorFactory() 0 4 1
A getSchemaManager() 0 4 1
A getClassNameResolver() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like DocumentManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DocumentManager, and based on these observations, apply Extract Interface, too.

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