Completed
Pull Request — master (#1419)
by Robert
39:37 queued 36:54
created

DocumentManager::flush()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.074

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 6
cp 0.8333
rs 9.2
c 0
b 0
f 0
cc 4
eloc 5
nc 2
nop 2
crap 4.074
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 1038
    protected function __construct(Connection $conn = null, Configuration $config = null, EventManager $eventManager = null)
145
    {
146 1038
        $this->config = $config ?: new Configuration();
147 1038
        $this->eventManager = $eventManager ?: new EventManager();
148 1038
        $this->connection = $conn ?: new Connection(null, array(), $this->config, $this->eventManager);
149
150 1038
        $metadataFactoryClassName = $this->config->getClassMetadataFactoryName();
151 1038
        $this->metadataFactory = new $metadataFactoryClassName();
152 1038
        $this->metadataFactory->setDocumentManager($this);
153 1038
        $this->metadataFactory->setConfiguration($this->config);
154 1038
        if ($cacheDriver = $this->config->getMetadataCacheImpl()) {
155
            $this->metadataFactory->setCacheDriver($cacheDriver);
156
        }
157
158 1038
        $hydratorDir = $this->config->getHydratorDir();
159 1038
        $hydratorNs = $this->config->getHydratorNamespace();
160 1038
        $this->hydratorFactory = new HydratorFactory(
161 1038
            $this,
162 1038
            $this->eventManager,
163 1038
            $hydratorDir,
164 1038
            $hydratorNs,
165 1038
            $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 1038
        );
167
168 1038
        $this->unitOfWork = new UnitOfWork($this, $this->eventManager, $this->hydratorFactory);
169 1038
        $this->hydratorFactory->setUnitOfWork($this->unitOfWork);
170 1038
        $this->schemaManager = new SchemaManager($this, $this->metadataFactory);
171 1038
        $this->proxyFactory = new ProxyFactory($this,
172 1038
            $this->config->getProxyDir(),
173 1038
            $this->config->getProxyNamespace(),
174 1038
            $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 1038
        );
176 1038
        $this->repositoryFactory = $this->config->getRepositoryFactory();
177 1038
    }
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 1038
    public static function create(Connection $conn = null, Configuration $config = null, EventManager $eventManager = null)
200
    {
201 1038
        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 1089
    public function getEventManager()
210
    {
211 1089
        return $this->eventManager;
212
    }
213
214
    /**
215
     * Gets the PHP Mongo instance that this DocumentManager wraps.
216
     *
217
     * @return \Doctrine\MongoDB\Connection
218
     */
219 1044
    public function getConnection()
220
    {
221 1044
        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 1038
    public function getMetadataFactory()
230
    {
231 1038
        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 1044
    public function getUnitOfWork()
252
    {
253 1044
        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 69
    public function getHydratorFactory()
263
    {
264 69
        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 54
    public function getSchemaManager()
273
    {
274 54
        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 815
    public function getClassMetadata($className)
285
    {
286 815
        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 756
    public function getDocumentDatabase($className)
296
    {
297 756
        $className = ltrim($className, '\\');
298
299 756
        if (isset($this->documentDatabases[$className])) {
300 213
            return $this->documentDatabases[$className];
301
        }
302
303 742
        $metadata = $this->metadataFactory->getMetadataFor($className);
304 742
        $db = $metadata->getDatabase();
305 742
        $db = $db ?: $this->config->getDefaultDB();
306 742
        $db = $db ?: 'doctrine';
307 742
        $this->documentDatabases[$className] = $this->connection->selectDatabase($db);
308
309 742
        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 747
    public function getDocumentCollection($className)
330
    {
331 747
        $className = ltrim($className, '\\');
332
333 747
        $metadata = $this->metadataFactory->getMetadataFor($className);
334 747
        $collectionName = $metadata->getCollection();
335
336 747
        if ( ! $collectionName) {
337
            throw MongoDBException::documentNotMappedToCollection($className);
338
        }
339
340 747
        if ( ! isset($this->documentCollections[$className])) {
341 738
            $db = $this->getDocumentDatabase($className);
342
343 738
            $this->documentCollections[$className] = $metadata->isFile()
344 738
                ? $db->getGridFS($collectionName)
345 738
                : $db->selectCollection($collectionName);
346 738
        }
347
348 747
        $collection = $this->documentCollections[$className];
349
350 747
        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 2
        }
353
354 747
        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 222
    public function createQueryBuilder($documentName = null)
374
    {
375 222
        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 606 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 606
        if ( ! is_object($document)) {
393 1
            throw new \InvalidArgumentException(gettype($document));
394
        }
395 605
        $this->errorIfClosed();
396 604
        $this->unitOfWork->persist($document);
397 600
    }
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 25 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 1
    {
410 25
        if ( ! is_object($document)) {
411 1
            throw new \InvalidArgumentException(gettype($document));
412
        }
413 24
        $this->errorIfClosed();
414 23
        $this->unitOfWork->remove($document);
415 23
    }
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 24 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 24
        if ( ! is_object($document)) {
427 1
            throw new \InvalidArgumentException(gettype($document));
428
        }
429 23
        $this->errorIfClosed();
430 22
        $this->unitOfWork->refresh($document);
431 21
    }
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 347
    public function getRepository($documentName)
507
    {
508 347
        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 585
    public function flush($document = null, array $options = array())
521
    {
522 585
        if (null !== $document && ! is_object($document) && ! is_array($document)) {
523
            throw new \InvalidArgumentException(gettype($document));
524
        }
525 585
        $this->errorIfClosed();
526 584
        $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 581
    }
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 118
    public function getReference($documentName, $identifier)
542
    {
543
        /* @var $class \Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo */
544 118
        $class = $this->metadataFactory->getMetadataFor(ltrim($documentName, '\\'));
545
546
        // Check identity map first, if its already in there just return it.
547 118
        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 44
            return $document;
549
        }
550
551 94
        $document = $this->proxyFactory->getProxy($class->name, array($class->identifier => $identifier));
552 93
        $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 93
        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 180
    public function find($documentName, $identifier, $lockMode = LockMode::NONE, $lockVersion = null)
603
    {
604 180
        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 399
    public function clear($documentName = null)
616
    {
617 399
        $this->unitOfWork->clear($documentName);
618 399
    }
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 739
    public function getConfiguration()
654
    {
655 739
        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 210
    public function createDBRef($document, array $referenceMapping = null)
668
    {
669 210
        if ( ! is_object($document)) {
670
            throw new \InvalidArgumentException('Cannot create a DBRef, the document is not an object');
671
        }
672
673 210
        $class = $this->getClassMetadata(get_class($document));
674 210
        $id = $this->unitOfWork->getDocumentIdentifier($document);
675
676 210
        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 1
            );
680
        }
681
682 209
        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 189
            '$ref' => $class->getCollection(),
691 189
            '$id'  => $class->getDatabaseIdentifierValue($id),
692 189
        );
693
694 189
        if ($referenceMapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF_WITH_DB) {
695 186
            $dbRef['$db'] = $this->getDocumentDatabase($class->name)->getName();
696 186
        }
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 189 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 17
                ? $class->discriminatorValue
705 17
                : $class->name;
706 17
        }
707
708
        /* Add a discriminator value if the referenced document is not mapped
709
         * explicitly to a targetDocument class.
710
         */
711 189 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 29
                ? 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 2
            }
726
727 29
            $dbRef[$discriminatorField] = $discriminatorValue;
728 29
        }
729
730 189
        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 613
    private function errorIfClosed()
739
    {
740 613
        if ($this->closed) {
741 5
            throw MongoDBException::documentManagerClosed();
742
        }
743 608
    }
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 504
    public function getFilterCollection()
761
    {
762 504
        if (null === $this->filterCollection) {
763 504
            $this->filterCollection = new FilterCollection($this);
764 504
        }
765
766 504
        return $this->filterCollection;
767
    }
768
}
769