Completed
Pull Request — master (#1410)
by Piotr
09:50
created

DocumentManager::createDBRef()   C

Complexity

Conditions 12
Paths 34

Size

Total Lines 65
Code Lines 30

Duplication

Lines 23
Ratio 35.38 %

Code Coverage

Tests 28
CRAP Score 12.0059

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 23
loc 65
ccs 28
cts 29
cp 0.9655
rs 5.9833
cc 12
eloc 30
nc 34
nop 2
crap 12.0059

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 970
    protected function __construct(Connection $conn = null, Configuration $config = null, EventManager $eventManager = null)
145
    {
146 970
        $this->config = $config ?: new Configuration();
147 970
        $this->eventManager = $eventManager ?: new EventManager();
148 970
        $this->connection = $conn ?: new Connection(null, array(), $this->config, $this->eventManager);
149
150 970
        $metadataFactoryClassName = $this->config->getClassMetadataFactoryName();
151 970
        $this->metadataFactory = new $metadataFactoryClassName();
152 970
        $this->metadataFactory->setDocumentManager($this);
153 970
        $this->metadataFactory->setConfiguration($this->config);
154 970
        if ($cacheDriver = $this->config->getMetadataCacheImpl()) {
155
            $this->metadataFactory->setCacheDriver($cacheDriver);
156
        }
157
158 970
        $hydratorDir = $this->config->getHydratorDir();
159 970
        $hydratorNs = $this->config->getHydratorNamespace();
160 970
        $this->hydratorFactory = new HydratorFactory(
161
            $this,
162 970
            $this->eventManager,
163
            $hydratorDir,
164
            $hydratorNs,
165 970
            $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
        );
167
168 970
        $this->unitOfWork = new UnitOfWork($this, $this->eventManager, $this->hydratorFactory);
169 970
        $this->hydratorFactory->setUnitOfWork($this->unitOfWork);
170 970
        $this->schemaManager = new SchemaManager($this, $this->metadataFactory);
171 970
        $this->proxyFactory = new ProxyFactory($this,
172 970
            $this->config->getProxyDir(),
173 970
            $this->config->getProxyNamespace(),
174 970
            $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
        );
176 970
        $this->repositoryFactory = $this->config->getRepositoryFactory();
177 970
    }
178
179
    /**
180
     * Gets the proxy factory used by the DocumentManager to create document proxies.
181
     *
182
     * @return ProxyFactory
183
     */
184 1
    public function getProxyFactory()
185
    {
186 1
        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 970
    public static function create(Connection $conn = null, Configuration $config = null, EventManager $eventManager = null)
200
    {
201 970
        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 1015
    public function getEventManager()
210
    {
211 1015
        return $this->eventManager;
212
    }
213
214
    /**
215
     * Gets the PHP Mongo instance that this DocumentManager wraps.
216
     *
217
     * @return \Doctrine\MongoDB\Connection
218
     */
219 970
    public function getConnection()
220
    {
221 970
        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 970
    public function getMetadataFactory()
230
    {
231 970
        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 976
    public function getUnitOfWork()
252
    {
253 976
        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 66
    public function getHydratorFactory()
263
    {
264 66
        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 44
    public function getSchemaManager()
273
    {
274 44
        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 780
    public function getClassMetadata($className)
285
    {
286 780
        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 721
    public function getDocumentDatabase($className)
296
    {
297 721
        $className = ltrim($className, '\\');
298
299 721
        if (isset($this->documentDatabases[$className])) {
300 195
            return $this->documentDatabases[$className];
301
        }
302
303 713
        $metadata = $this->metadataFactory->getMetadataFor($className);
304 713
        $db = $metadata->getDatabase();
305 713
        $db = $db ?: $this->config->getDefaultDB();
306 713
        $db = $db ?: 'doctrine';
307 713
        $this->documentDatabases[$className] = $this->connection->selectDatabase($db);
308
309 713
        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 718
    public function getDocumentCollection($className)
330
    {
331 718
        $className = ltrim($className, '\\');
332
333 718
        $metadata = $this->metadataFactory->getMetadataFor($className);
334 718
        $collectionName = $metadata->getCollection();
335
336 718
        if ( ! $collectionName) {
337
            throw MongoDBException::documentNotMappedToCollection($className);
338
        }
339
340 718
        if ( ! isset($this->documentCollections[$className])) {
341 709
            $db = $this->getDocumentDatabase($className);
342
343 709
            $this->documentCollections[$className] = $metadata->isFile()
344 12
                ? $db->getGridFS($collectionName)
345 702
                : $db->selectCollection($collectionName);
346
        }
347
348 718
        $collection = $this->documentCollections[$className];
349
350 718
        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 2
            $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 718
        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 220
    public function createQueryBuilder($documentName = null)
374
    {
375 220
        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 584 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 584
        if ( ! is_object($document)) {
393 1
            throw new \InvalidArgumentException(gettype($document));
394
        }
395 583
        $this->errorIfClosed();
396 582
        $this->unitOfWork->persist($document);
397 578
    }
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 20 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 20
        if ( ! is_object($document)) {
411 1
            throw new \InvalidArgumentException(gettype($document));
412
        }
413 19
        $this->errorIfClosed();
414 18
        $this->unitOfWork->remove($document);
415 18
    }
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 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...
425
    {
426 23
        if ( ! is_object($document)) {
427 1
            throw new \InvalidArgumentException(gettype($document));
428
        }
429 22
        $this->errorIfClosed();
430 21
        $this->unitOfWork->refresh($document);
431 20
    }
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 9
    public function detach($document)
444
    {
445 9
        if ( ! is_object($document)) {
446 1
            throw new \InvalidArgumentException(gettype($document));
447
        }
448 8
        $this->unitOfWork->detach($document);
449 8
    }
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 15 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 15
        if ( ! is_object($document)) {
464 1
            throw new \InvalidArgumentException(gettype($document));
465
        }
466 14
        $this->errorIfClosed();
467 13
        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 9
    public function lock($document, $lockMode, $lockVersion = null)
479
    {
480 9
        if ( ! is_object($document)) {
481
            throw new \InvalidArgumentException(gettype($document));
482
        }
483 9
        $this->unitOfWork->lock($document, $lockMode, $lockVersion);
484 6
    }
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 1
    public function unlock($document)
493
    {
494 1
        if ( ! is_object($document)) {
495
            throw new \InvalidArgumentException(gettype($document));
496
        }
497 1
        $this->unitOfWork->unlock($document);
498 1
    }
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 346
    public function getRepository($documentName)
507
    {
508 346
        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 563
    public function flush($document = null, array $options = array())
521
    {
522 563
        if (null !== $document && ! is_object($document) && ! is_array($document)) {
523
            throw new \InvalidArgumentException(gettype($document));
524
        }
525 563
        $this->errorIfClosed();
526 562
        $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 559
    }
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 116
    public function getReference($documentName, $identifier)
542
    {
543
        /* @var $class \Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo */
544 116
        $class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
545
546
        // Check identity map first, if its already in there just return it.
547 116
        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 42
            return $document;
549
        }
550
551 92
        $document = $this->proxyFactory->getProxy($class->name, array($class->identifier => $identifier));
552 92
        $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 92
        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 1
    public function getPartialReference($documentName, $identifier)
577
    {
578 1
        $class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
579
580
        // Check identity map first, if its already in there just return it.
581 1
        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 1
        $document = $class->newInstance();
585 1
        $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 1
        $this->unitOfWork->registerManaged($document, $identifier, array());
587
588 1
        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 179
    public function find($documentName, $identifier, $lockMode = LockMode::NONE, $lockVersion = null)
603
    {
604 179
        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 398
    public function clear($documentName = null)
616
    {
617 398
        $this->unitOfWork->clear($documentName);
618 398
    }
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 6
    public function close()
626
    {
627 6
        $this->clear();
628 6
        $this->closed = true;
629 6
    }
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 6
    public function contains($document)
639
    {
640 6
        if ( ! is_object($document)) {
641
            throw new \InvalidArgumentException(gettype($document));
642
        }
643 6
        return $this->unitOfWork->isScheduledForInsert($document) ||
644 6
            $this->unitOfWork->isInIdentityMap($document) &&
645 6
            ! $this->unitOfWork->isScheduledForDelete($document);
646
    }
647
648
    /**
649
     * Gets the Configuration used by the DocumentManager.
650
     *
651
     * @return Configuration
652
     */
653 718
    public function getConfiguration()
654
    {
655 718
        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 208
    public function createDBRef($document, array $referenceMapping = null)
668
    {
669 208
        if ( ! is_object($document)) {
670
            throw new \InvalidArgumentException('Cannot create a DBRef, the document is not an object');
671
        }
672
673 208
        $class = $this->getClassMetadata(get_class($document));
674 208
        $id = $this->unitOfWork->getDocumentIdentifier($document);
675
676 208
        if ( ! $id) {
677 1
            throw new \RuntimeException(
678 1
                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 207
        if ($referenceMapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID) {
683 27
            if ($class->inheritanceType === ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_COLLECTION) {
684 1
                throw MappingException::simpleReferenceMustNotTargetDiscriminatedDocument($referenceMapping['targetDocument']);
685
            }
686 26
            return $class->getDatabaseIdentifierValue($id);
687
        }
688
689
        $dbRef = array(
690 187
            '$ref' => $class->getCollection(),
691 187
            '$id'  => $class->getDatabaseIdentifierValue($id),
692
        );
693
694 187
        if ($referenceMapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF_WITH_DB) {
695 184
            $dbRef['$db'] = $this->getDocumentDatabase($class->name)->getName();
696
        }
697
698
        /* If the class has a discriminator (field and value), use it. A child
699
         * class that is not defined in the discriminator map may only have a
700
         * discriminator field and no value, so default to the full class name.
701
         */
702 187 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...
703 17
            $dbRef[$class->discriminatorField] = isset($class->discriminatorValue)
704 15
                ? $class->discriminatorValue
705 4
                : $class->name;
706
        }
707
708
        /* Add a discriminator value if the referenced document is not mapped
709
         * explicitly to a targetDocument class.
710
         */
711 187 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...
712 29
            $discriminatorField = $referenceMapping['discriminatorField'];
713 29
            $discriminatorValue = isset($referenceMapping['discriminatorMap'])
714 8
                ? array_search($class->name, $referenceMapping['discriminatorMap'])
715 29
                : $class->name;
716
717
            /* If the discriminator value was not found in the map, use the full
718
             * class name. In the future, it may be preferable to throw an
719
             * exception here (perhaps based on some strictness option).
720
             *
721
             * @see PersistenceBuilder::prepareEmbeddedDocumentValue()
722
             */
723 29
            if ($discriminatorValue === false) {
724 2
                $discriminatorValue = $class->name;
725
            }
726
727 29
            $dbRef[$discriminatorField] = $discriminatorValue;
728
        }
729
730 187
        return $dbRef;
731
    }
732
733
    /**
734
     * Throws an exception if the DocumentManager is closed or currently not active.
735
     *
736
     * @throws MongoDBException If the DocumentManager is closed.
737
     */
738 591
    private function errorIfClosed()
739
    {
740 591
        if ($this->closed) {
741 5
            throw MongoDBException::documentManagerClosed();
742
        }
743 586
    }
744
745
    /**
746
     * Check if the Document manager is open or closed.
747
     *
748
     * @return bool
749
     */
750 1
    public function isOpen()
751
    {
752 1
        return ( ! $this->closed);
753
    }
754
755
    /**
756
     * Gets the filter collection.
757
     *
758
     * @return \Doctrine\ODM\MongoDB\Query\FilterCollection The active filter collection.
759
     */
760 502
    public function getFilterCollection()
761
    {
762 502
        if (null === $this->filterCollection) {
763 502
            $this->filterCollection = new FilterCollection($this);
764
        }
765
766 502
        return $this->filterCollection;
767
    }
768
}
769