Completed
Push — master ( 420611...4009e3 )
by Andreas
11s
created

DocumentManager   D

Complexity

Total Complexity 72

Size/Duplication

Total Lines 748
Duplicated Lines 6.68 %

Coupling/Cohesion

Components 3
Dependencies 12

Test Coverage

Coverage 92.5%

Importance

Changes 0
Metric Value
wmc 72
lcom 3
cbo 12
dl 50
loc 748
ccs 185
cts 200
cp 0.925
rs 4.3636
c 0
b 0
f 0

37 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 34 5
A getProxyFactory() 0 4 1
A create() 0 4 1
A getEventManager() 0 4 1
A getClient() 0 4 1
A getMetadataFactory() 0 4 1
A initializeObject() 0 4 1
A getUnitOfWork() 0 4 1
A getHydratorFactory() 0 4 1
A getSchemaManager() 0 4 1
A getClassMetadata() 0 4 1
A getDocumentDatabase() 0 16 4
A getDocumentDatabases() 0 4 1
B getDocumentCollection() 0 24 4
A getDocumentCollections() 0 4 1
A createQueryBuilder() 0 4 1
A createAggregationBuilder() 0 4 1
A persist() 8 8 2
A remove() 8 8 2
A refresh() 8 8 2
A detach() 0 7 2
A merge() 8 8 2
A lock() 0 7 2
A unlock() 0 7 2
A getRepository() 0 4 1
A flush() 0 5 1
A getReference() 0 15 2
A getPartialReference() 0 14 2
A find() 0 4 1
A clear() 0 4 1
A close() 0 5 1
A contains() 0 9 4
A getConfiguration() 0 4 1
C createReference() 18 82 12
A errorIfClosed() 0 6 2
A isOpen() 0 4 1
A getFilterCollection() 0 8 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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
namespace Doctrine\ODM\MongoDB;
4
5
use Doctrine\Common\EventManager;
6
use Doctrine\Common\Persistence\ObjectManager;
7
use Doctrine\Common\Persistence\ObjectRepository;
8
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
9
use Doctrine\ODM\MongoDB\Mapping\MappingException;
10
use Doctrine\ODM\MongoDB\Hydrator\HydratorFactory;
11
use Doctrine\ODM\MongoDB\Proxy\ProxyFactory;
12
use Doctrine\ODM\MongoDB\Query\FilterCollection;
13
use Doctrine\ODM\MongoDB\Repository\RepositoryFactory;
14
use MongoDB\Client;
15
use MongoDB\Collection;
16
use MongoDB\Database;
17
use MongoDB\Driver\ReadPreference;
18
19
/**
20
 * The DocumentManager class is the central access point for managing the
21
 * persistence of documents.
22
 *
23
 *     <?php
24
 *
25
 *     $config = new Configuration();
26
 *     $dm = DocumentManager::create(new Connection(), $config);
27
 *
28
 * @since       1.0
29
 */
30
class DocumentManager implements ObjectManager
31
{
32
    /**
33
     * The Doctrine MongoDB connection instance.
34
     *
35
     * @var Client
36
     */
37
    private $client;
38
39
    /**
40
     * The used Configuration.
41
     *
42
     * @var \Doctrine\ODM\MongoDB\Configuration
43
     */
44
    private $config;
45
46
    /**
47
     * The metadata factory, used to retrieve the ODM metadata of document classes.
48
     *
49
     * @var \Doctrine\ODM\MongoDB\Mapping\ClassMetadataFactory
50
     */
51
    private $metadataFactory;
52
53
    /**
54
     * The UnitOfWork used to coordinate object-level transactions.
55
     *
56
     * @var UnitOfWork
57
     */
58
    private $unitOfWork;
59
60
    /**
61
     * The event manager that is the central point of the event system.
62
     *
63
     * @var \Doctrine\Common\EventManager
64
     */
65
    private $eventManager;
66
67
    /**
68
     * The Hydrator factory instance.
69
     *
70
     * @var HydratorFactory
71
     */
72
    private $hydratorFactory;
73
74
    /**
75
     * The Proxy factory instance.
76
     *
77
     * @var ProxyFactory
78
     */
79
    private $proxyFactory;
80
81
    /**
82
     * The repository factory used to create dynamic repositories.
83
     *
84
     * @var RepositoryFactory
85
     */
86
    private $repositoryFactory;
87
88
    /**
89
     * SchemaManager instance
90
     *
91
     * @var SchemaManager
92
     */
93
    private $schemaManager;
94
95
    /**
96
     * Array of cached document database instances that are lazily loaded.
97
     *
98
     * @var Database[]
99
     */
100
    private $documentDatabases = array();
101
102
    /**
103
     * Array of cached document collection instances that are lazily loaded.
104
     *
105
     * @var Collection[]
106
     */
107
    private $documentCollections = array();
108
109
    /**
110
     * Whether the DocumentManager is closed or not.
111
     *
112
     * @var bool
113
     */
114
    private $closed = false;
115
116
    /**
117
     * Collection of query filters.
118
     *
119
     * @var \Doctrine\ODM\MongoDB\Query\FilterCollection
120
     */
121
    private $filterCollection;
122
123
    /**
124
     * Creates a new Document that operates on the given Mongo connection
125
     * and uses the given Configuration.
126
     *
127
     * @param Client|null $client
128
     * @param Configuration|null $config
129
     * @param \Doctrine\Common\EventManager|null $eventManager
130
     */
131 1576
    protected function __construct(Client $client = null, Configuration $config = null, EventManager $eventManager = null)
132
    {
133 1576
        $this->config = $config ?: new Configuration();
134 1576
        $this->eventManager = $eventManager ?: new EventManager();
135 1576
        $this->client = $client ?: new Client('mongodb://127.0.0.1', [], ['typeMap' => ['root' => 'array', 'document' => 'array']]);
136
137 1576
        $metadataFactoryClassName = $this->config->getClassMetadataFactoryName();
138 1576
        $this->metadataFactory = new $metadataFactoryClassName();
139 1576
        $this->metadataFactory->setDocumentManager($this);
140 1576
        $this->metadataFactory->setConfiguration($this->config);
141 1576
        if ($cacheDriver = $this->config->getMetadataCacheImpl()) {
142
            $this->metadataFactory->setCacheDriver($cacheDriver);
143
        }
144
145 1576
        $hydratorDir = $this->config->getHydratorDir();
146 1576
        $hydratorNs = $this->config->getHydratorNamespace();
147 1576
        $this->hydratorFactory = new HydratorFactory(
148 1576
            $this,
149 1576
            $this->eventManager,
150 1576
            $hydratorDir,
151 1576
            $hydratorNs,
152 1576
            $this->config->getAutoGenerateHydratorClasses()
0 ignored issues
show
Bug introduced by
It seems like $this->config->getAutoGenerateHydratorClasses() targeting Doctrine\ODM\MongoDB\Con...nerateHydratorClasses() can also be of type boolean; however, Doctrine\ODM\MongoDB\Hyd...rFactory::__construct() does only seem to accept integer, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
153
        );
154
155 1576
        $this->unitOfWork = new UnitOfWork($this, $this->eventManager, $this->hydratorFactory);
156 1576
        $this->hydratorFactory->setUnitOfWork($this->unitOfWork);
157 1576
        $this->schemaManager = new SchemaManager($this, $this->metadataFactory);
158 1576
        $this->proxyFactory = new ProxyFactory($this,
159 1576
            $this->config->getProxyDir(),
160 1576
            $this->config->getProxyNamespace(),
161 1576
            $this->config->getAutoGenerateProxyClasses()
162
        );
163 1576
        $this->repositoryFactory = $this->config->getRepositoryFactory();
164 1576
    }
165
166
    /**
167
     * Gets the proxy factory used by the DocumentManager to create document proxies.
168
     *
169
     * @return ProxyFactory
170
     */
171 1
    public function getProxyFactory()
172
    {
173 1
        return $this->proxyFactory;
174
    }
175
176
    /**
177
     * Creates a new Document that operates on the given Mongo connection
178
     * and uses the given Configuration.
179
     *
180
     * @static
181
     * @param Client|null $client
182
     * @param Configuration|null $config
183
     * @param \Doctrine\Common\EventManager|null $eventManager
184
     * @return DocumentManager
185
     */
186 1576
    public static function create(Client $client = null, Configuration $config = null, EventManager $eventManager = null)
187
    {
188 1576
        return new static($client, $config, $eventManager);
189
    }
190
191
    /**
192
     * Gets the EventManager used by the DocumentManager.
193
     *
194
     * @return \Doctrine\Common\EventManager
195
     */
196 1619
    public function getEventManager()
197
    {
198 1619
        return $this->eventManager;
199
    }
200
201
    /**
202
     * Gets the MongoDB client instance that this DocumentManager wraps.
203
     *
204
     * @return Client
205
     */
206 1576
    public function getClient()
207
    {
208 1576
        return $this->client;
209
    }
210
211
    /**
212
     * Gets the metadata factory used to gather the metadata of classes.
213
     *
214
     * @return \Doctrine\ODM\MongoDB\Mapping\ClassMetadataFactory
215
     */
216 1576
    public function getMetadataFactory()
217
    {
218 1576
        return $this->metadataFactory;
219
    }
220
221
    /**
222
     * Helper method to initialize a lazy loading proxy or persistent collection.
223
     *
224
     * This method is a no-op for other objects.
225
     *
226
     * @param object $obj
227
     */
228
    public function initializeObject($obj)
229
    {
230
        $this->unitOfWork->initializeObject($obj);
231
    }
232
233
    /**
234
     * Gets the UnitOfWork used by the DocumentManager to coordinate operations.
235
     *
236
     * @return UnitOfWork
237
     */
238 1582
    public function getUnitOfWork()
239
    {
240 1582
        return $this->unitOfWork;
241
    }
242
243
    /**
244
     * Gets the Hydrator factory used by the DocumentManager to generate and get hydrators
245
     * for each type of document.
246
     *
247
     * @return HydratorFactory
248
     */
249 66
    public function getHydratorFactory()
250
    {
251 66
        return $this->hydratorFactory;
252
    }
253
254
    /**
255
     * Returns SchemaManager, used to create/drop indexes/collections/databases.
256
     *
257
     * @return \Doctrine\ODM\MongoDB\SchemaManager
258
     */
259 18
    public function getSchemaManager()
260
    {
261 18
        return $this->schemaManager;
262
    }
263
264
    /**
265
     * Returns the metadata for a class.
266
     *
267
     * @param string $className The class name.
268
     * @return \Doctrine\ODM\MongoDB\Mapping\ClassMetadata
269
     * @internal Performance-sensitive method.
270
     */
271 1318
    public function getClassMetadata($className)
272
    {
273 1318
        return $this->metadataFactory->getMetadataFor(ltrim($className, '\\'));
274
    }
275
276
    /**
277
     * Returns the MongoDB instance for a class.
278
     *
279
     * @param string $className The class name.
280
     * @return Database
281
     */
282 1252
    public function getDocumentDatabase($className)
283
    {
284 1252
        $className = ltrim($className, '\\');
285
286 1252
        if (isset($this->documentDatabases[$className])) {
287 35
            return $this->documentDatabases[$className];
288
        }
289
290 1248
        $metadata = $this->metadataFactory->getMetadataFor($className);
291 1248
        $db = $metadata->getDatabase();
292 1248
        $db = $db ?: $this->config->getDefaultDB();
293 1248
        $db = $db ?: 'doctrine';
294 1248
        $this->documentDatabases[$className] = $this->client->selectDatabase($db);
295
296 1248
        return $this->documentDatabases[$className];
297
    }
298
299
    /**
300
     * Gets the array of instantiated document database instances.
301
     *
302
     * @return Database[]
303
     */
304
    public function getDocumentDatabases()
305
    {
306
        return $this->documentDatabases;
307
    }
308
309
    /**
310
     * Returns the MongoCollection instance for a class.
311
     *
312
     * @param string $className The class name.
313
     * @throws MongoDBException When the $className param is not mapped to a collection
314
     * @return Collection
315
     */
316 1254
    public function getDocumentCollection($className)
317
    {
318 1254
        $className = ltrim($className, '\\');
319
320 1254
        $metadata = $this->metadataFactory->getMetadataFor($className);
321 1254
        $collectionName = $metadata->getCollection();
322
323 1254
        if ( ! $collectionName) {
324
            throw MongoDBException::documentNotMappedToCollection($className);
325
        }
326
327 1254
        if ( ! isset($this->documentCollections[$className])) {
328 1244
            $db = $this->getDocumentDatabase($className);
329
330 1244
            $options = [];
331 1244
            if ($metadata->readPreference !== null) {
332 3
                $options['readPreference'] = new ReadPreference($metadata->readPreference, $metadata->readPreferenceTags);
333
            }
334
335 1244
            $this->documentCollections[$className] = $db->selectCollection($collectionName, $options);
336
        }
337
338 1254
        return $this->documentCollections[$className];
339
    }
340
341
    /**
342
     * Gets the array of instantiated document collection instances.
343
     *
344
     * @return Collection[]
345
     */
346
    public function getDocumentCollections()
347
    {
348
        return $this->documentCollections;
349
    }
350
351
    /**
352
     * Create a new Query instance for a class.
353
     *
354
     * @param string $documentName The document class name.
355
     * @return Query\Builder
356
     */
357 178
    public function createQueryBuilder($documentName = null)
358
    {
359 178
        return new Query\Builder($this, $documentName);
360
    }
361
362
    /**
363
     * Creates a new aggregation builder instance for a class.
364
     *
365
     * @param string $documentName The document class name.
366
     * @return Aggregation\Builder
367
     */
368 41
    public function createAggregationBuilder($documentName)
369
    {
370 41
        return new Aggregation\Builder($this, $documentName);
371
    }
372
373
    /**
374
     * Tells the DocumentManager to make an instance managed and persistent.
375
     *
376
     * The document will be entered into the database at or before transaction
377
     * commit or as a result of the flush operation.
378
     *
379
     * NOTE: The persist operation always considers documents that are not yet known to
380
     * this DocumentManager as NEW. Do not pass detached documents to the persist operation.
381
     *
382
     * @param object $document The instance to make managed and persistent.
383
     * @throws \InvalidArgumentException When the given $document param is not an object
384
     */
385 579 View Code Duplication
    public function persist($document)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
386
    {
387 579
        if ( ! is_object($document)) {
388 1
            throw new \InvalidArgumentException(gettype($document));
389
        }
390 578
        $this->errorIfClosed();
391 577
        $this->unitOfWork->persist($document);
392 573
    }
393
394
    /**
395
     * Removes a document instance.
396
     *
397
     * A removed document will be removed from the database at or before transaction commit
398
     * or as a result of the flush operation.
399
     *
400
     * @param object $document The document instance to remove.
401
     * @throws \InvalidArgumentException when the $document param is not an object
402
     */
403 23 View Code Duplication
    public function remove($document)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
404
    {
405 23
        if ( ! is_object($document)) {
406 1
            throw new \InvalidArgumentException(gettype($document));
407
        }
408 22
        $this->errorIfClosed();
409 21
        $this->unitOfWork->remove($document);
410 21
    }
411
412
    /**
413
     * Refreshes the persistent state of a document from the database,
414
     * overriding any local changes that have not yet been persisted.
415
     *
416
     * @param object $document The document to refresh.
417
     * @throws \InvalidArgumentException When the given $document param is not an object
418
     */
419 23 View Code Duplication
    public function refresh($document)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
420
    {
421 23
        if ( ! is_object($document)) {
422 1
            throw new \InvalidArgumentException(gettype($document));
423
        }
424 22
        $this->errorIfClosed();
425 21
        $this->unitOfWork->refresh($document);
426 20
    }
427
428
    /**
429
     * Detaches a document from the DocumentManager, causing a managed document to
430
     * become detached.  Unflushed changes made to the document if any
431
     * (including removal of the document), will not be synchronized to the database.
432
     * Documents which previously referenced the detached document will continue to
433
     * reference it.
434
     *
435
     * @param object $document The document to detach.
436
     * @throws \InvalidArgumentException when the $document param is not an object
437
     */
438 11
    public function detach($document)
439
    {
440 11
        if ( ! is_object($document)) {
441 1
            throw new \InvalidArgumentException(gettype($document));
442
        }
443 10
        $this->unitOfWork->detach($document);
444 10
    }
445
446
    /**
447
     * Merges the state of a detached document into the persistence context
448
     * of this DocumentManager and returns the managed copy of the document.
449
     * The document passed to merge will not become associated/managed with this DocumentManager.
450
     *
451
     * @param object $document The detached document to merge into the persistence context.
452
     * @throws LockException
453
     * @throws \InvalidArgumentException if the $document param is not an object
454
     * @return object The managed copy of the document.
455
     */
456 14 View Code Duplication
    public function merge($document)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
457
    {
458 14
        if ( ! is_object($document)) {
459 1
            throw new \InvalidArgumentException(gettype($document));
460
        }
461 13
        $this->errorIfClosed();
462 12
        return $this->unitOfWork->merge($document);
463
    }
464
465
    /**
466
     * Acquire a lock on the given document.
467
     *
468
     * @param object $document
469
     * @param int $lockMode
470
     * @param int $lockVersion
471
     * @throws \InvalidArgumentException
472
     */
473 8
    public function lock($document, $lockMode, $lockVersion = null)
474
    {
475 8
        if ( ! is_object($document)) {
476
            throw new \InvalidArgumentException(gettype($document));
477
        }
478 8
        $this->unitOfWork->lock($document, $lockMode, $lockVersion);
479 5
    }
480
481
    /**
482
     * Releases a lock on the given document.
483
     *
484
     * @param object $document
485
     * @throws \InvalidArgumentException if the $document param is not an object
486
     */
487 1
    public function unlock($document)
488
    {
489 1
        if ( ! is_object($document)) {
490
            throw new \InvalidArgumentException(gettype($document));
491
        }
492 1
        $this->unitOfWork->unlock($document);
493 1
    }
494
495
    /**
496
     * Gets the repository for a document class.
497
     *
498
     * @param string $documentName  The name of the Document.
499
     * @return ObjectRepository  The repository.
500
     */
501 325
    public function getRepository($documentName)
502
    {
503 325
        return $this->repositoryFactory->getRepository($this, $documentName);
504
    }
505
506
    /**
507
     * Flushes all changes to objects that have been queued up to now to the database.
508
     * This effectively synchronizes the in-memory state of managed objects with the
509
     * database.
510
     *
511
     * @param array $options Array of options to be used with batchInsert(), update() and remove()
512
     * @throws \InvalidArgumentException
513
     */
514 550
    public function flush(array $options = array())
515
    {
516 550
        $this->errorIfClosed();
517 549
        $this->unitOfWork->commit($options);
518 546
    }
519
520
    /**
521
     * Gets a reference to the document identified by the given type and identifier
522
     * without actually loading it.
523
     *
524
     * If partial objects are allowed, this method will return a partial object that only
525
     * has its identifier populated. Otherwise a proxy is returned that automatically
526
     * loads itself on first access.
527
     *
528
     * @param string $documentName
529
     * @param string|object $identifier
530
     * @return mixed|object The document reference.
531
     */
532 125
    public function getReference($documentName, $identifier)
533
    {
534
        /* @var $class \Doctrine\ODM\MongoDB\Mapping\ClassMetadata */
535 125
        $class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
536
537
        // Check identity map first, if its already in there just return it.
538 125
        if ($document = $this->unitOfWork->tryGetById($identifier, $class)) {
539 55
            return $document;
540
        }
541
542 96
        $document = $this->proxyFactory->getProxy($class->name, array($class->identifier => $identifier));
543 96
        $this->unitOfWork->registerManaged($document, $identifier, array());
544
545 96
        return $document;
546
    }
547
548
    /**
549
     * Gets a partial reference to the document identified by the given type and identifier
550
     * without actually loading it, if the document is not yet loaded.
551
     *
552
     * The returned reference may be a partial object if the document is not yet loaded/managed.
553
     * If it is a partial object it will not initialize the rest of the document state on access.
554
     * Thus you can only ever safely access the identifier of a document obtained through
555
     * this method.
556
     *
557
     * The use-cases for partial references involve maintaining bidirectional associations
558
     * without loading one side of the association or to update a document without loading it.
559
     * Note, however, that in the latter case the original (persistent) document data will
560
     * never be visible to the application (especially not event listeners) as it will
561
     * never be loaded in the first place.
562
     *
563
     * @param string $documentName The name of the document type.
564
     * @param mixed $identifier The document identifier.
565
     * @return object The (partial) document reference.
566
     */
567 1
    public function getPartialReference($documentName, $identifier)
568
    {
569 1
        $class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
570
571
        // Check identity map first, if its already in there just return it.
572 1
        if ($document = $this->unitOfWork->tryGetById($identifier, $class)) {
573
            return $document;
574
        }
575 1
        $document = $class->newInstance();
576 1
        $class->setIdentifierValue($document, $identifier);
577 1
        $this->unitOfWork->registerManaged($document, $identifier, array());
578
579 1
        return $document;
580
    }
581
582
    /**
583
     * Finds a Document by its identifier.
584
     *
585
     * This is just a convenient shortcut for getRepository($documentName)->find($id).
586
     *
587
     * @param string $documentName
588
     * @param mixed $identifier
589
     * @param int $lockMode
590
     * @param int $lockVersion
591
     * @return object $document
592
     */
593 181
    public function find($documentName, $identifier, $lockMode = LockMode::NONE, $lockVersion = null)
594
    {
595 181
        return $this->getRepository($documentName)->find($identifier, $lockMode, $lockVersion);
596
    }
597
598
    /**
599
     * Clears the DocumentManager.
600
     *
601
     * All documents that are currently managed by this DocumentManager become
602
     * detached.
603
     *
604
     * @param string|null $documentName if given, only documents of this type will get detached
605
     */
606 371
    public function clear($documentName = null)
607
    {
608 371
        $this->unitOfWork->clear($documentName);
609 371
    }
610
611
    /**
612
     * Closes the DocumentManager. All documents that are currently managed
613
     * by this DocumentManager become detached. The DocumentManager may no longer
614
     * be used after it is closed.
615
     */
616 6
    public function close()
617
    {
618 6
        $this->clear();
619 6
        $this->closed = true;
620 6
    }
621
622
    /**
623
     * Determines whether a document instance is managed in this DocumentManager.
624
     *
625
     * @param object $document
626
     * @throws \InvalidArgumentException When the $document param is not an object
627
     * @return boolean TRUE if this DocumentManager currently manages the given document, FALSE otherwise.
628
     */
629 3
    public function contains($document)
630
    {
631 3
        if ( ! is_object($document)) {
632
            throw new \InvalidArgumentException(gettype($document));
633
        }
634 3
        return $this->unitOfWork->isScheduledForInsert($document) ||
635 3
            $this->unitOfWork->isInIdentityMap($document) &&
636 3
            ! $this->unitOfWork->isScheduledForDelete($document);
637
    }
638
639
    /**
640
     * Gets the Configuration used by the DocumentManager.
641
     *
642
     * @return Configuration
643
     */
644 717
    public function getConfiguration()
645
    {
646 717
        return $this->config;
647
    }
648
649
    /**
650
     * Returns a reference to the supplied document.
651
     *
652
     * @param object $document A document object
653
     * @param array $referenceMapping Mapping for the field that references the document
654
     *
655
     * @throws \InvalidArgumentException
656
     * @throws MappingException
657
     * @return mixed The reference for the document in question, according to the desired mapping
658
     */
659 220
    public function createReference($document, array $referenceMapping)
660
    {
661 220
        if ( ! is_object($document)) {
662
            throw new \InvalidArgumentException('Cannot create a DBRef, the document is not an object');
663
        }
664
665 220
        $class = $this->getClassMetadata(get_class($document));
666 220
        $id = $this->unitOfWork->getDocumentIdentifier($document);
667
668 220
        if ($id === null) {
669 1
            throw new \RuntimeException(
670 1
                sprintf('Cannot create a DBRef for class %s without an identifier. Have you forgotten to persist/merge the document first?', $class->name)
671
            );
672
        }
673
674 219
        $storeAs = $referenceMapping['storeAs'] ?? null;
675 219
        $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...
676 219
        switch ($storeAs) {
677
            case ClassMetadata::REFERENCE_STORE_AS_ID:
678 45
                if ($class->inheritanceType === ClassMetadata::INHERITANCE_TYPE_SINGLE_COLLECTION) {
679 1
                    throw MappingException::simpleReferenceMustNotTargetDiscriminatedDocument($referenceMapping['targetDocument']);
680
                }
681
682 44
                return $class->getDatabaseIdentifierValue($id);
683
                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...
684
685
686
            case ClassMetadata::REFERENCE_STORE_AS_REF:
687 19
                $reference = ['id' => $class->getDatabaseIdentifierValue($id)];
688 19
                break;
689
690
            case ClassMetadata::REFERENCE_STORE_AS_DB_REF:
691
                $reference = [
692 176
                    '$ref' => $class->getCollection(),
693 176
                    '$id'  => $class->getDatabaseIdentifierValue($id),
694
                ];
695 176
                break;
696
697
            case ClassMetadata::REFERENCE_STORE_AS_DB_REF_WITH_DB:
698
                $reference = [
699 17
                    '$ref' => $class->getCollection(),
700 17
                    '$id'  => $class->getDatabaseIdentifierValue($id),
701 17
                    '$db'  => $this->getDocumentDatabase($class->name)->getDatabaseName(),
702
                ];
703 17
                break;
704
705
            default:
706
                throw new \InvalidArgumentException("Reference type {$storeAs} is invalid.");
707
        }
708
709
        /* If the class has a discriminator (field and value), use it. A child
710
         * class that is not defined in the discriminator map may only have a
711
         * discriminator field and no value, so default to the full class name.
712
         */
713 197
        if (isset($class->discriminatorField)) {
714 18
            $reference[$class->discriminatorField] = $class->discriminatorValue ?? $class->name;
715
        }
716
717
        /* Add a discriminator value if the referenced document is not mapped
718
         * explicitly to a targetDocument class.
719
         */
720 197 View Code Duplication
        if (! isset($referenceMapping['targetDocument'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
721 33
            $discriminatorField = $referenceMapping['discriminatorField'];
722 33
            $discriminatorValue = isset($referenceMapping['discriminatorMap'])
723 8
                ? array_search($class->name, $referenceMapping['discriminatorMap'])
724 33
                : $class->name;
725
726
            /* If the discriminator value was not found in the map, use the full
727
             * class name. In the future, it may be preferable to throw an
728
             * exception here (perhaps based on some strictness option).
729
             *
730
             * @see PersistenceBuilder::prepareEmbeddedDocumentValue()
731
             */
732 33
            if ($discriminatorValue === false) {
733 2
                $discriminatorValue = $class->name;
734
            }
735
736 33
            $reference[$discriminatorField] = $discriminatorValue;
737
        }
738
739 197
        return $reference;
740
    }
741
742
    /**
743
     * Throws an exception if the DocumentManager is closed or currently not active.
744
     *
745
     * @throws MongoDBException If the DocumentManager is closed.
746
     */
747 583
    private function errorIfClosed()
748
    {
749 583
        if ($this->closed) {
750 5
            throw MongoDBException::documentManagerClosed();
751
        }
752 578
    }
753
754
    /**
755
     * Check if the Document manager is open or closed.
756
     *
757
     * @return bool
758
     */
759 1
    public function isOpen()
760
    {
761 1
        return ( ! $this->closed);
762
    }
763
764
    /**
765
     * Gets the filter collection.
766
     *
767
     * @return \Doctrine\ODM\MongoDB\Query\FilterCollection The active filter collection.
768
     */
769 502
    public function getFilterCollection()
770
    {
771 502
        if (null === $this->filterCollection) {
772 502
            $this->filterCollection = new FilterCollection($this);
773
        }
774
775 502
        return $this->filterCollection;
776
    }
777
}
778