Completed
Pull Request — 1.0.x (#1416)
by Maciej
09:32
created

DocumentManager::getMetadataFactory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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