Completed
Pull Request — master (#1376)
by Bilge
30:49 queued 28:17
created

DocumentManager::getReference()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6
Metric Value
dl 0
loc 15
ccs 0
cts 7
cp 0
rs 9.4285
cc 2
eloc 7
nc 2
nop 2
crap 6
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\ODM\MongoDB;
21
22
use Doctrine\Common\EventManager;
23
use Doctrine\Common\Persistence\ObjectManager;
24
use Doctrine\MongoDB\Connection;
25
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo;
26
use Doctrine\ODM\MongoDB\Mapping\MappingException;
27
use Doctrine\ODM\MongoDB\Hydrator\HydratorFactory;
28
use Doctrine\ODM\MongoDB\Proxy\ProxyFactory;
29
use Doctrine\ODM\MongoDB\Query\FilterCollection;
30
use Doctrine\ODM\MongoDB\Repository\RepositoryFactory;
31
32
/**
33
 * The DocumentManager class is the central access point for managing the
34
 * persistence of documents.
35
 *
36
 *     <?php
37
 *
38
 *     $config = new Configuration();
39
 *     $dm = DocumentManager::create(new Connection(), $config);
40
 *
41
 * @since       1.0
42
 */
43
class DocumentManager implements ObjectManager
44
{
45
    /**
46
     * The Doctrine MongoDB connection instance.
47
     *
48
     * @var \Doctrine\MongoDB\Connection
49
     */
50
    private $connection;
51
52
    /**
53
     * The used Configuration.
54
     *
55
     * @var \Doctrine\ODM\MongoDB\Configuration
56
     */
57
    private $config;
58
59
    /**
60
     * The metadata factory, used to retrieve the ODM metadata of document classes.
61
     *
62
     * @var \Doctrine\ODM\MongoDB\Mapping\ClassMetadataFactory
63
     */
64
    private $metadataFactory;
65
66
    /**
67
     * The UnitOfWork used to coordinate object-level transactions.
68
     *
69
     * @var UnitOfWork
70
     */
71
    private $unitOfWork;
72
73
    /**
74
     * The event manager that is the central point of the event system.
75
     *
76
     * @var \Doctrine\Common\EventManager
77
     */
78
    private $eventManager;
79
80
    /**
81
     * The Hydrator factory instance.
82
     *
83
     * @var HydratorFactory
84
     */
85
    private $hydratorFactory;
86
87
    /**
88
     * The Proxy factory instance.
89
     *
90
     * @var ProxyFactory
91
     */
92
    private $proxyFactory;
93
94
    /**
95
     * The repository factory used to create dynamic repositories.
96
     *
97
     * @var RepositoryFactory
98
     */
99
    private $repositoryFactory;
100
101
    /**
102
     * SchemaManager instance
103
     *
104
     * @var SchemaManager
105
     */
106
    private $schemaManager;
107
108
    /**
109
     * Array of cached document database instances that are lazily loaded.
110
     *
111
     * @var array
112
     */
113
    private $documentDatabases = array();
114
115
    /**
116
     * Array of cached document collection instances that are lazily loaded.
117
     *
118
     * @var array
119
     */
120
    private $documentCollections = array();
121
122
    /**
123
     * Whether the DocumentManager is closed or not.
124
     *
125
     * @var bool
126
     */
127
    private $closed = false;
128
129
    /**
130
     * Collection of query filters.
131
     *
132
     * @var \Doctrine\ODM\MongoDB\Query\FilterCollection
133
     */
134
    private $filterCollection;
135
136
    /**
137
     * Creates a new Document that operates on the given Mongo connection
138
     * and uses the given Configuration.
139
     *
140
     * @param \Doctrine\MongoDB\Connection|null $conn
141
     * @param Configuration|null $config
142
     * @param \Doctrine\Common\EventManager|null $eventManager
143
     */
144 2
    protected function __construct(Connection $conn = null, Configuration $config = null, EventManager $eventManager = null)
145
    {
146 2
        $this->config = $config ?: new Configuration();
147 2
        $this->eventManager = $eventManager ?: new EventManager();
148 2
        $this->connection = $conn ?: new Connection(null, array(), $this->config, $this->eventManager);
149
150 2
        $metadataFactoryClassName = $this->config->getClassMetadataFactoryName();
151 2
        $this->metadataFactory = new $metadataFactoryClassName();
152 2
        $this->metadataFactory->setDocumentManager($this);
153 2
        $this->metadataFactory->setConfiguration($this->config);
154 2
        if ($cacheDriver = $this->config->getMetadataCacheImpl()) {
155
            $this->metadataFactory->setCacheDriver($cacheDriver);
156
        }
157
158 2
        $hydratorDir = $this->config->getHydratorDir();
159 2
        $hydratorNs = $this->config->getHydratorNamespace();
160 2
        $this->hydratorFactory = new HydratorFactory(
161 2
            $this,
162 2
            $this->eventManager,
163 2
            $hydratorDir,
164 2
            $hydratorNs,
165 2
            $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...
166 2
        );
167
168 2
        $this->unitOfWork = new UnitOfWork($this, $this->eventManager, $this->hydratorFactory);
169 2
        $this->hydratorFactory->setUnitOfWork($this->unitOfWork);
170 2
        $this->schemaManager = new SchemaManager($this, $this->metadataFactory);
171 2
        $this->proxyFactory = new ProxyFactory($this,
172 2
            $this->config->getProxyDir(),
173 2
            $this->config->getProxyNamespace(),
174 2
            $this->config->getAutoGenerateProxyClasses()
0 ignored issues
show
Bug introduced by
It seems like $this->config->getAutoGenerateProxyClasses() targeting Doctrine\ODM\MongoDB\Con...oGenerateProxyClasses() can also be of type boolean; however, Doctrine\ODM\MongoDB\Pro...yFactory::__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...
175 2
        );
176 2
        $this->repositoryFactory = $this->config->getRepositoryFactory();
177 2
    }
178
179
    /**
180
     * Gets the proxy factory used by the DocumentManager to create document proxies.
181
     *
182
     * @return ProxyFactory
183
     */
184
    public function getProxyFactory()
185
    {
186
        return $this->proxyFactory;
187
    }
188
189
    /**
190
     * Creates a new Document that operates on the given Mongo connection
191
     * and uses the given Configuration.
192
     *
193
     * @static
194
     * @param \Doctrine\MongoDB\Connection|null $conn
195
     * @param Configuration|null $config
196
     * @param \Doctrine\Common\EventManager|null $eventManager
197
     * @return DocumentManager
198
     */
199 2
    public static function create(Connection $conn = null, Configuration $config = null, EventManager $eventManager = null)
200
    {
201 2
        return new static($conn, $config, $eventManager);
202
    }
203
204
    /**
205
     * Gets the EventManager used by the DocumentManager.
206
     *
207
     * @return \Doctrine\Common\EventManager
208
     */
209 2
    public function getEventManager()
210
    {
211 2
        return $this->eventManager;
212
    }
213
214
    /**
215
     * Gets the PHP Mongo instance that this DocumentManager wraps.
216
     *
217
     * @return \Doctrine\MongoDB\Connection
218
     */
219 2
    public function getConnection()
220
    {
221 2
        return $this->connection;
222
    }
223
224
    /**
225
     * Gets the metadata factory used to gather the metadata of classes.
226
     *
227
     * @return \Doctrine\ODM\MongoDB\Mapping\ClassMetadataFactory
228
     */
229 2
    public function getMetadataFactory()
230
    {
231 2
        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
     * @return UnitOfWork
250
     */
251 2
    public function getUnitOfWork()
252
    {
253 2
        return $this->unitOfWork;
254
    }
255
256
    /**
257
     * Gets the Hydrator factory used by the DocumentManager to generate and get hydrators
258
     * for each type of document.
259
     *
260
     * @return \Doctrine\ODM\MongoDB\Hydrator\HydratorInterface
261
     */
262
    public function getHydratorFactory()
263
    {
264
        return $this->hydratorFactory;
265
    }
266
267
    /**
268
     * Returns SchemaManager, used to create/drop indexes/collections/databases.
269
     *
270
     * @return \Doctrine\ODM\MongoDB\SchemaManager
271
     */
272
    public function getSchemaManager()
273
    {
274
        return $this->schemaManager;
275
    }
276
277
    /**
278
     * Returns the metadata for a class.
279
     *
280
     * @param string $className The class name.
281
     * @return \Doctrine\ODM\MongoDB\Mapping\ClassMetadata
282
     * @internal Performance-sensitive method.
283
     */
284 2
    public function getClassMetadata($className)
285
    {
286 2
        return $this->metadataFactory->getMetadataFor(ltrim($className, '\\'));
287
    }
288
289
    /**
290
     * Returns the MongoDB instance for a class.
291
     *
292
     * @param string $className The class name.
293
     * @return \Doctrine\MongoDB\Database
294
     */
295 2
    public function getDocumentDatabase($className)
296
    {
297 2
        $className = ltrim($className, '\\');
298
299 2
        if (isset($this->documentDatabases[$className])) {
300
            return $this->documentDatabases[$className];
301
        }
302
303 2
        $metadata = $this->metadataFactory->getMetadataFor($className);
304 2
        $db = $metadata->getDatabase();
305 2
        $db = $db ? $db : $this->config->getDefaultDB();
306 2
        $db = $db ? $db : 'doctrine';
307 2
        $this->documentDatabases[$className] = $this->connection->selectDatabase($db);
308
309 2
        return $this->documentDatabases[$className];
310
    }
311
312
    /**
313
     * Gets the array of instantiated document database instances.
314
     *
315
     * @return array
316
     */
317
    public function getDocumentDatabases()
318
    {
319
        return $this->documentDatabases;
320
    }
321
322
    /**
323
     * Returns the MongoCollection instance for a class.
324
     *
325
     * @param string $className The class name.
326
     * @throws MongoDBException When the $className param is not mapped to a collection
327
     * @return \Doctrine\MongoDB\Collection
328
     */
329 2
    public function getDocumentCollection($className)
330
    {
331 2
        $className = ltrim($className, '\\');
332
333 2
        $metadata = $this->metadataFactory->getMetadataFor($className);
334 2
        $collectionName = $metadata->getCollection();
335
336 2
        if ( ! $collectionName) {
337
            throw MongoDBException::documentNotMappedToCollection($className);
338
        }
339
340 2
        if ( ! isset($this->documentCollections[$className])) {
341 2
            $db = $this->getDocumentDatabase($className);
342
343 2
            $this->documentCollections[$className] = $metadata->isFile()
344 2
                ? $db->getGridFS($collectionName)
345 2
                : $db->selectCollection($collectionName);
346 2
        }
347
348 2
        $collection = $this->documentCollections[$className];
349
350 2
        if ($metadata->slaveOkay !== null) {
0 ignored issues
show
Bug introduced by
Accessing slaveOkay on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
351
            $collection->setSlaveOkay($metadata->slaveOkay);
0 ignored issues
show
Bug introduced by
Accessing slaveOkay on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
352
        }
353
354 2
        return $this->documentCollections[$className];
355
    }
356
357
    /**
358
     * Gets the array of instantiated document collection instances.
359
     *
360
     * @return array
361
     */
362
    public function getDocumentCollections()
363
    {
364
        return $this->documentCollections;
365
    }
366
367
    /**
368
     * Create a new Query instance for a class.
369
     *
370
     * @param string $documentName The document class name.
371
     * @return Query\Builder
372
     */
373
    public function createQueryBuilder($documentName = null)
374
    {
375
        return new Query\Builder($this, $documentName);
376
    }
377
378
    /**
379
     * Tells the DocumentManager to make an instance managed and persistent.
380
     *
381
     * The document will be entered into the database at or before transaction
382
     * commit or as a result of the flush operation.
383
     *
384
     * NOTE: The persist operation always considers documents that are not yet known to
385
     * this DocumentManager as NEW. Do not pass detached documents to the persist operation.
386
     *
387
     * @param object $document The instance to make managed and persistent.
388
     * @throws \InvalidArgumentException When the given $document param is not an object
389
     */
390 2 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...
391
    {
392 2
        if ( ! is_object($document)) {
393
            throw new \InvalidArgumentException(gettype($document));
394
        }
395 2
        $this->errorIfClosed();
396 2
        $this->unitOfWork->persist($document);
397 2
    }
398
399
    /**
400
     * Removes a document instance.
401
     *
402
     * A removed document will be removed from the database at or before transaction commit
403
     * or as a result of the flush operation.
404
     *
405
     * @param object $document The document instance to remove.
406
     * @throws \InvalidArgumentException when the $document param is not an object
407
     */
408 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...
409
    {
410
        if ( ! is_object($document)) {
411
            throw new \InvalidArgumentException(gettype($document));
412
        }
413
        $this->errorIfClosed();
414
        $this->unitOfWork->remove($document);
415
    }
416
417
    /**
418
     * Refreshes the persistent state of a document from the database,
419
     * overriding any local changes that have not yet been persisted.
420
     *
421
     * @param object $document The document to refresh.
422
     * @throws \InvalidArgumentException When the given $document param is not an object
423
     */
424 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...
425
    {
426
        if ( ! is_object($document)) {
427
            throw new \InvalidArgumentException(gettype($document));
428
        }
429
        $this->errorIfClosed();
430
        $this->unitOfWork->refresh($document);
431
    }
432
433
    /**
434
     * Detaches a document from the DocumentManager, causing a managed document to
435
     * become detached.  Unflushed changes made to the document if any
436
     * (including removal of the document), will not be synchronized to the database.
437
     * Documents which previously referenced the detached document will continue to
438
     * reference it.
439
     *
440
     * @param object $document The document to detach.
441
     * @throws \InvalidArgumentException when the $document param is not an object
442
     */
443
    public function detach($document)
444
    {
445
        if ( ! is_object($document)) {
446
            throw new \InvalidArgumentException(gettype($document));
447
        }
448
        $this->unitOfWork->detach($document);
449
    }
450
451
    /**
452
     * Merges the state of a detached document into the persistence context
453
     * of this DocumentManager and returns the managed copy of the document.
454
     * The document passed to merge will not become associated/managed with this DocumentManager.
455
     *
456
     * @param object $document The detached document to merge into the persistence context.
457
     * @throws LockException
458
     * @throws \InvalidArgumentException if the $document param is not an object
459
     * @return object The managed copy of the document.
460
     */
461 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...
462
    {
463
        if ( ! is_object($document)) {
464
            throw new \InvalidArgumentException(gettype($document));
465
        }
466
        $this->errorIfClosed();
467
        return $this->unitOfWork->merge($document);
468
    }
469
470
    /**
471
     * Acquire a lock on the given document.
472
     *
473
     * @param object $document
474
     * @param int $lockMode
475
     * @param int $lockVersion
476
     * @throws \InvalidArgumentException
477
     */
478 1
    public function lock($document, $lockMode, $lockVersion = null)
479
    {
480
        if ( ! is_object($document)) {
481
            throw new \InvalidArgumentException(gettype($document));
482
        }
483 1
        $this->unitOfWork->lock($document, $lockMode, $lockVersion);
484
    }
485
486
    /**
487
     * Releases a lock on the given document.
488
     *
489
     * @param object $document
490
     * @throws \InvalidArgumentException if the $document param is not an object
491
     */
492
    public function unlock($document)
493
    {
494
        if ( ! is_object($document)) {
495
            throw new \InvalidArgumentException(gettype($document));
496
        }
497
        $this->unitOfWork->unlock($document);
498
    }
499
500
    /**
501
     * Gets the repository for a document class.
502
     *
503
     * @param string $documentName  The name of the Document.
504
     * @return DocumentRepository  The repository.
505
     */
506 2
    public function getRepository($documentName)
507
    {
508 2
        return $this->repositoryFactory->getRepository($this, $documentName);
509
    }
510
511
    /**
512
     * Flushes all changes to objects that have been queued up to now to the database.
513
     * This effectively synchronizes the in-memory state of managed objects with the
514
     * database.
515
     *
516
     * @param object $document
517
     * @param array $options Array of options to be used with batchInsert(), update() and remove()
518
     * @throws \InvalidArgumentException
519
     */
520 2
    public function flush($document = null, array $options = array())
521
    {
522 2
        if (null !== $document && ! is_object($document) && ! is_array($document)) {
523
            throw new \InvalidArgumentException(gettype($document));
524
        }
525 2
        $this->errorIfClosed();
526 2
        $this->unitOfWork->commit($document, $options);
0 ignored issues
show
Bug introduced by
It seems like $document can also be of type array; however, Doctrine\ODM\MongoDB\UnitOfWork::commit() does only seem to accept object|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
527 2
    }
528
529
    /**
530
     * Gets a reference to the document identified by the given type and identifier
531
     * without actually loading it.
532
     *
533
     * If partial objects are allowed, this method will return a partial object that only
534
     * has its identifier populated. Otherwise a proxy is returned that automatically
535
     * loads itself on first access.
536
     *
537
     * @param string $documentName
538
     * @param string|object $identifier
539
     * @return mixed|object The document reference.
540
     */
541
    public function getReference($documentName, $identifier)
542
    {
543
        /* @var $class \Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo */
544
        $class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
545
546
        // Check identity map first, if its already in there just return it.
547
        if ($document = $this->unitOfWork->tryGetById($identifier, $class)) {
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\ODM\Mong...ping\ClassMetadataInfo> is not a sub-type of object<Doctrine\ODM\Mong...\Mapping\ClassMetadata>. It seems like you assume a child class of the class Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
548
            return $document;
549
        }
550
551
        $document = $this->proxyFactory->getProxy($class->name, array($class->identifier => $identifier));
552
        $this->unitOfWork->registerManaged($document, $identifier, array());
0 ignored issues
show
Documentation introduced by
$identifier is of type string|object, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
553
554
        return $document;
555
    }
556
557
    /**
558
     * Gets a partial reference to the document identified by the given type and identifier
559
     * without actually loading it, if the document is not yet loaded.
560
     *
561
     * The returned reference may be a partial object if the document is not yet loaded/managed.
562
     * If it is a partial object it will not initialize the rest of the document state on access.
563
     * Thus you can only ever safely access the identifier of a document obtained through
564
     * this method.
565
     *
566
     * The use-cases for partial references involve maintaining bidirectional associations
567
     * without loading one side of the association or to update a document without loading it.
568
     * Note, however, that in the latter case the original (persistent) document data will
569
     * never be visible to the application (especially not event listeners) as it will
570
     * never be loaded in the first place.
571
     *
572
     * @param string $documentName The name of the document type.
573
     * @param mixed $identifier The document identifier.
574
     * @return object The (partial) document reference.
575
     */
576
    public function getPartialReference($documentName, $identifier)
577
    {
578
        $class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
579
580
        // Check identity map first, if its already in there just return it.
581
        if ($document = $this->unitOfWork->tryGetById($identifier, $class)) {
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...\Mapping\ClassMetadata>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
582
            return $document;
583
        }
584
        $document = $class->newInstance();
585
        $class->setIdentifierValue($document, $identifier);
0 ignored issues
show
Bug introduced by
The method setIdentifierValue() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. Did you maybe mean getIdentifierValues()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
586
        $this->unitOfWork->registerManaged($document, $identifier, array());
587
588
        return $document;
589
    }
590
591
    /**
592
     * Finds a Document by its identifier.
593
     *
594
     * This is just a convenient shortcut for getRepository($documentName)->find($id).
595
     *
596
     * @param string $documentName
597
     * @param mixed $identifier
598
     * @param int $lockMode
599
     * @param int $lockVersion
600
     * @return object $document
601
     */
602 2
    public function find($documentName, $identifier, $lockMode = LockMode::NONE, $lockVersion = null)
603
    {
604 2
        return $this->getRepository($documentName)->find($identifier, $lockMode, $lockVersion);
605
    }
606
607
    /**
608
     * Clears the DocumentManager.
609
     *
610
     * All documents that are currently managed by this DocumentManager become
611
     * detached.
612
     *
613
     * @param string|null $documentName if given, only documents of this type will get detached
614
     */
615 2
    public function clear($documentName = null)
616
    {
617 2
        $this->unitOfWork->clear($documentName);
618 2
    }
619
620
    /**
621
     * Closes the DocumentManager. All documents that are currently managed
622
     * by this DocumentManager become detached. The DocumentManager may no longer
623
     * be used after it is closed.
624
     */
625
    public function close()
626
    {
627
        $this->clear();
628
        $this->closed = true;
629
    }
630
631
    /**
632
     * Determines whether a document instance is managed in this DocumentManager.
633
     *
634
     * @param object $document
635
     * @throws \InvalidArgumentException When the $document param is not an object
636
     * @return boolean TRUE if this DocumentManager currently manages the given document, FALSE otherwise.
637
     */
638
    public function contains($document)
639
    {
640
        if ( ! is_object($document)) {
641
            throw new \InvalidArgumentException(gettype($document));
642
        }
643
        return $this->unitOfWork->isScheduledForInsert($document) ||
644
            $this->unitOfWork->isInIdentityMap($document) &&
645
            ! $this->unitOfWork->isScheduledForDelete($document);
646
    }
647
648
    /**
649
     * Gets the Configuration used by the DocumentManager.
650
     *
651
     * @return Configuration
652
     */
653 2
    public function getConfiguration()
654
    {
655 2
        return $this->config;
656
    }
657
658
    /**
659
     * Returns a DBRef array for the supplied document.
660
     *
661
     * @param mixed $document A document object
662
     * @param array $referenceMapping Mapping for the field that references the document
663
     *
664
     * @throws \InvalidArgumentException
665
     * @return array A DBRef array
666
     */
667
    public function createDBRef($document, array $referenceMapping = null)
668
    {
669
        if ( ! is_object($document)) {
670
            throw new \InvalidArgumentException('Cannot create a DBRef, the document is not an object');
671
        }
672
673
        $class = $this->getClassMetadata(get_class($document));
674
        $id = $this->unitOfWork->getDocumentIdentifier($document);
675
676
        if ( ! $id) {
677
            throw new \RuntimeException(
678
                sprintf('Cannot create a DBRef for class %s without an identifier. Have you forgotten to persist/merge the document first?', $class->name)
679
            );
680
        }
681
682
        if ( ! empty($referenceMapping['simple'])) {
683
            if ($class->inheritanceType === ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_COLLECTION) {
684
                throw MappingException::simpleReferenceMustNotTargetDiscriminatedDocument($referenceMapping['targetDocument']);
685
            }
686
            return $class->getDatabaseIdentifierValue($id);
687
        }
688
689
        $dbRef = array(
690
            '$ref' => $class->getCollection(),
691
            '$id'  => $class->getDatabaseIdentifierValue($id),
692
            '$db'  => $this->getDocumentDatabase($class->name)->getName(),
693
        );
694
695
        /* If the class has a discriminator (field and value), use it. A child
696
         * class that is not defined in the discriminator map may only have a
697
         * discriminator field and no value, so default to the full class name.
698
         */
699 View Code Duplication
        if (isset($class->discriminatorField)) {
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...
700
            $dbRef[$class->discriminatorField] = isset($class->discriminatorValue)
701
                ? $class->discriminatorValue
702
                : $class->name;
703
        }
704
705
        /* Add a discriminator value if the referenced document is not mapped
706
         * explicitly to a targetDocument class.
707
         */
708 View Code Duplication
        if ($referenceMapping !== null && ! 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...
709
            $discriminatorField = $referenceMapping['discriminatorField'];
710
            $discriminatorValue = isset($referenceMapping['discriminatorMap'])
711
                ? array_search($class->name, $referenceMapping['discriminatorMap'])
712
                : $class->name;
713
714
            /* If the discriminator value was not found in the map, use the full
715
             * class name. In the future, it may be preferable to throw an
716
             * exception here (perhaps based on some strictness option).
717
             *
718
             * @see PersistenceBuilder::prepareEmbeddedDocumentValue()
719
             */
720
            if ($discriminatorValue === false) {
721
                $discriminatorValue = $class->name;
722
            }
723
724
            $dbRef[$discriminatorField] = $discriminatorValue;
725
        }
726
727
        return $dbRef;
728
    }
729
730
    /**
731
     * Throws an exception if the DocumentManager is closed or currently not active.
732
     *
733
     * @throws MongoDBException If the DocumentManager is closed.
734
     */
735 2
    private function errorIfClosed()
736
    {
737 2
        if ($this->closed) {
738
            throw MongoDBException::documentManagerClosed();
739
        }
740 2
    }
741
742
    /**
743
     * Check if the Document manager is open or closed.
744
     *
745
     * @return bool
746
     */
747
    public function isOpen()
748
    {
749
        return ( ! $this->closed);
750
    }
751
752
    /**
753
     * Gets the filter collection.
754
     *
755
     * @return \Doctrine\ODM\MongoDB\Query\FilterCollection The active filter collection.
756
     */
757 2
    public function getFilterCollection()
758
    {
759 2
        if (null === $this->filterCollection) {
760 2
            $this->filterCollection = new FilterCollection($this);
761 2
        }
762
763 2
        return $this->filterCollection;
764
    }
765
}
766