Completed
Pull Request — master (#5860)
by Peter
10:08
created

EntityManager::getCache()   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
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
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\ORM;
21
22
use Exception;
23
use Doctrine\Common\EventManager;
24
use Doctrine\DBAL\Connection;
25
use Doctrine\DBAL\DriverManager;
26
use Doctrine\DBAL\LockMode;
27
use Doctrine\ORM\Query\ResultSetMapping;
28
use Doctrine\ORM\Proxy\ProxyFactory;
29
use Doctrine\ORM\Query\FilterCollection;
30
use Doctrine\Common\Util\ClassUtils;
31
32
/**
33
 * The EntityManager is the central access point to ORM functionality.
34
 *
35
 * It is a facade to all different ORM subsystems such as UnitOfWork,
36
 * Query Language and Repository API. Instantiation is done through
37
 * the static create() method. The quickest way to obtain a fully
38
 * configured EntityManager is:
39
 *
40
 *     use Doctrine\ORM\Tools\Setup;
41
 *     use Doctrine\ORM\EntityManager;
42
 *
43
 *     $paths = array('/path/to/entity/mapping/files');
44
 *
45
 *     $config = Setup::createAnnotationMetadataConfiguration($paths);
46
 *     $dbParams = array('driver' => 'pdo_sqlite', 'memory' => true);
47
 *     $entityManager = EntityManager::create($dbParams, $config);
48
 *
49
 * For more information see
50
 * {@link http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/configuration.html}
51
 *
52
 * You should never attempt to inherit from the EntityManager: Inheritance
53
 * is not a valid extension point for the EntityManager. Instead you
54
 * should take a look at the {@see \Doctrine\ORM\Decorator\EntityManagerDecorator}
55
 * and wrap your entity manager in a decorator.
56
 *
57
 * @since   2.0
58
 * @author  Benjamin Eberlei <[email protected]>
59
 * @author  Guilherme Blanco <[email protected]>
60
 * @author  Jonathan Wage <[email protected]>
61
 * @author  Roman Borschel <[email protected]>
62
 */
63
/* final */class EntityManager implements EntityManagerInterface
64
{
65
    /**
66
     * The used Configuration.
67
     *
68
     * @var \Doctrine\ORM\Configuration
69
     */
70
    private $config;
71
72
    /**
73
     * The database connection used by the EntityManager.
74
     *
75
     * @var \Doctrine\DBAL\Connection
76
     */
77
    private $conn;
78
79
    /**
80
     * The metadata factory, used to retrieve the ORM metadata of entity classes.
81
     *
82
     * @var \Doctrine\ORM\Mapping\ClassMetadataFactory
83
     */
84
    private $metadataFactory;
85
86
    /**
87
     * The UnitOfWork used to coordinate object-level transactions.
88
     *
89
     * @var \Doctrine\ORM\UnitOfWork
90
     */
91
    private $unitOfWork;
92
93
    /**
94
     * The event manager that is the central point of the event system.
95
     *
96
     * @var \Doctrine\Common\EventManager
97
     */
98
    private $eventManager;
99
100
    /**
101
     * The proxy factory used to create dynamic proxies.
102
     *
103
     * @var \Doctrine\ORM\Proxy\ProxyFactory
104
     */
105
    private $proxyFactory;
106
107
    /**
108
     * The repository factory used to create dynamic repositories.
109
     *
110
     * @var \Doctrine\ORM\Repository\RepositoryFactory
111
     */
112
    private $repositoryFactory;
113
114
    /**
115
     * The expression builder instance used to generate query expressions.
116
     *
117
     * @var \Doctrine\ORM\Query\Expr
118
     */
119
    private $expressionBuilder;
120
121
    /**
122
     * Whether the EntityManager is closed or not.
123
     *
124
     * @var bool
125
     */
126
    private $closed = false;
127
128
    /**
129
     * Collection of query filters.
130
     *
131
     * @var \Doctrine\ORM\Query\FilterCollection
132
     */
133
    private $filterCollection;
134
135
    /**
136
     * @var \Doctrine\ORM\Cache The second level cache regions API.
137
     */
138
    private $cache;
139
140
    /**
141
     * Creates a new EntityManager that operates on the given database connection
142
     * and uses the given Configuration and EventManager implementations.
143
     *
144
     * @param \Doctrine\DBAL\Connection     $conn
145
     * @param \Doctrine\ORM\Configuration   $config
146
     * @param \Doctrine\Common\EventManager $eventManager
147
     */
148 2324
    protected function __construct(Connection $conn, Configuration $config, EventManager $eventManager)
149
    {
150 2324
        $this->conn              = $conn;
151 2324
        $this->config            = $config;
152 2324
        $this->eventManager      = $eventManager;
153
154 2324
        $metadataFactoryClassName = $config->getClassMetadataFactoryName();
155
156 2324
        $this->metadataFactory = new $metadataFactoryClassName;
157 2324
        $this->metadataFactory->setEntityManager($this);
158 2324
        $this->metadataFactory->setCacheDriver($this->config->getMetadataCacheImpl());
159
160 2324
        $this->repositoryFactory = $config->getRepositoryFactory();
161 2324
        $this->unitOfWork        = new UnitOfWork($this);
162 2324
        $this->proxyFactory      = new ProxyFactory(
163
            $this,
164 2324
            $config->getProxyDir(),
165 2324
            $config->getProxyNamespace(),
166 2324
            $config->getAutoGenerateProxyClasses()
167
        );
168
169 2324
        if ($config->isSecondLevelCacheEnabled()) {
170 275
            $cacheConfig    = $config->getSecondLevelCacheConfiguration();
171 275
            $cacheFactory   = $cacheConfig->getCacheFactory();
172 275
            $this->cache    = $cacheFactory->createCache($this);
173
        }
174 2324
    }
175
176
    /**
177
     * {@inheritDoc}
178
     */
179 1827
    public function getConnection()
180
    {
181 1827
        return $this->conn;
182
    }
183
184
    /**
185
     * Gets the metadata factory used to gather the metadata of classes.
186
     *
187
     * @return \Doctrine\ORM\Mapping\ClassMetadataFactory
188
     */
189 2324
    public function getMetadataFactory()
190
    {
191 2324
        return $this->metadataFactory;
192
    }
193
194
    /**
195
     * {@inheritDoc}
196
     */
197 17
    public function getExpressionBuilder()
198
    {
199 17
        if ($this->expressionBuilder === null) {
200 17
            $this->expressionBuilder = new Query\Expr;
201
        }
202
203 17
        return $this->expressionBuilder;
204
    }
205
206
    /**
207
     * {@inheritDoc}
208
     */
209 2
    public function beginTransaction()
210
    {
211 2
        $this->conn->beginTransaction();
212 2
    }
213
214
    /**
215
     * {@inheritDoc}
216
     */
217 210
    public function getCache()
218
    {
219 210
        return $this->cache;
220
    }
221
222
    /**
223
     * {@inheritDoc}
224
     */
225 4
    public function transactional($func)
226
    {
227 4
        if (!is_callable($func)) {
228 1
            throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"');
229
        }
230
231 3
        $this->conn->beginTransaction();
232
233
        try {
234 3
            $return = call_user_func($func, $this);
235
236 3
            $this->flush();
237 3
            $this->conn->commit();
238
239 3
            return $return ?: true;
240
        } catch (Exception $e) {
241
            $this->close();
242
            $this->conn->rollBack();
243
244
            throw $e;
245
        }
246
    }
247
248
    /**
249
     * {@inheritDoc}
250
     */
251 1
    public function commit()
252
    {
253 1
        $this->conn->commit();
254 1
    }
255
256
    /**
257
     * {@inheritDoc}
258
     */
259 1
    public function rollback()
260
    {
261 1
        $this->conn->rollBack();
262 1
    }
263
264
    /**
265
     * Returns the ORM metadata descriptor for a class.
266
     *
267
     * The class name must be the fully-qualified class name without a leading backslash
268
     * (as it is returned by get_class($obj)) or an aliased class name.
269
     *
270
     * Examples:
271
     * MyProject\Domain\User
272
     * sales:PriceRequest
273
     *
274
     * Internal note: Performance-sensitive method.
275
     *
276
     * @param string $className
277
     *
278
     * @return \Doctrine\ORM\Mapping\ClassMetadata
279
     */
280 1881
    public function getClassMetadata($className)
281
    {
282 1881
        return $this->metadataFactory->getMetadataFor($className);
283
    }
284
285
    /**
286
     * {@inheritDoc}
287
     */
288 921
    public function createQuery($dql = '')
289
    {
290 921
        $query = new Query($this);
291
292 921
        if ( ! empty($dql)) {
293 916
            $query->setDql($dql);
294
        }
295
296 921
        return $query;
297
    }
298
299
    /**
300
     * {@inheritDoc}
301
     */
302 1
    public function createNamedQuery($name)
303
    {
304 1
        return $this->createQuery($this->config->getNamedQuery($name));
305
    }
306
307
    /**
308
     * {@inheritDoc}
309
     */
310 21
    public function createNativeQuery($sql, ResultSetMapping $rsm)
311
    {
312 21
        $query = new NativeQuery($this);
313
314 21
        $query->setSql($sql);
315 21
        $query->setResultSetMapping($rsm);
316
317 21
        return $query;
318
    }
319
320
    /**
321
     * {@inheritDoc}
322
     */
323 1
    public function createNamedNativeQuery($name)
324
    {
325 1
        list($sql, $rsm) = $this->config->getNamedNativeQuery($name);
326
327 1
        return $this->createNativeQuery($sql, $rsm);
328
    }
329
330
    /**
331
     * {@inheritDoc}
332
     */
333 112
    public function createQueryBuilder()
334
    {
335 112
        return new QueryBuilder($this);
336
    }
337
338
    /**
339
     * Flushes all changes to objects that have been queued up to now to the database.
340
     * This effectively synchronizes the in-memory state of managed objects with the
341
     * database.
342
     *
343
     * If an entity is explicitly passed to this method only this entity and
344
     * the cascade-persist semantics + scheduled inserts/removals are synchronized.
345
     *
346
     * @param null|object|array $entity
347
     *
348
     * @return void
349
     *
350
     * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that
351
     *         makes use of optimistic locking fails.
352
     * @throws ORMException
353
     */
354 1009
    public function flush($entity = null)
355
    {
356 1009
        $this->errorIfClosed();
357
358 1008
        $this->unitOfWork->commit($entity);
359 999
    }
360
361
    /**
362
     * Finds an Entity by its identifier.
363
     *
364
     * @param string       $entityName  The class name of the entity to find.
365
     * @param mixed        $id          The identity of the entity to find.
366
     * @param integer|null $lockMode    One of the \Doctrine\DBAL\LockMode::* constants
367
     *                                  or NULL if no specific lock mode should be used
368
     *                                  during the search.
369
     * @param integer|null $lockVersion The version of the entity to find when using
370
     *                                  optimistic locking.
371
     *
372
     * @return object|null The entity instance or NULL if the entity can not be found.
373
     *
374
     * @throws OptimisticLockException
375
     * @throws ORMInvalidArgumentException
376
     * @throws TransactionRequiredException
377
     * @throws ORMException
378
     */
379 409
    public function find($entityName, $id, $lockMode = null, $lockVersion = null)
380
    {
381 409
        $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
382
383 409
        if ( ! is_array($id)) {
384 365
            if ($class->isIdentifierComposite) {
0 ignored issues
show
Bug introduced by
Accessing isIdentifierComposite 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...
385
                throw ORMInvalidArgumentException::invalidCompositeIdentifier();
386
            }
387
388 365
            $id = array($class->identifier[0] => $id);
0 ignored issues
show
Bug introduced by
Accessing identifier 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...
389
        }
390
391 409
        foreach ($id as $i => $value) {
392 409
            if (is_object($value) && $this->metadataFactory->hasMetadataFor(ClassUtils::getClass($value))) {
393 6
                $id[$i] = $this->unitOfWork->getSingleIdentifierValue($value);
394
395 6
                if ($id[$i] === null) {
396 409
                    throw ORMInvalidArgumentException::invalidIdentifierBindingEntity();
397
                }
398
            }
399
        }
400
401 408
        $sortedId = array();
402
403 408
        foreach ($class->identifier as $identifier) {
0 ignored issues
show
Bug introduced by
Accessing identifier 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...
404 408
            if ( ! isset($id[$identifier])) {
405 1
                throw ORMException::missingIdentifierField($class->name, $identifier);
0 ignored issues
show
Bug introduced by
Accessing name 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...
406
            }
407
408 407
            $sortedId[$identifier] = $id[$identifier];
409 407
            unset($id[$identifier]);
410
        }
411
412 407
        if ($id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
413 1
            throw ORMException::unrecognizedIdentifierFields($class->name, array_keys($id));
0 ignored issues
show
Bug introduced by
Accessing name 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...
414
        }
415
416 406
        $unitOfWork = $this->getUnitOfWork();
417
418
        // Check identity map first
419 406
        if (($entity = $unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) {
0 ignored issues
show
Bug introduced by
Accessing rootEntityName 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...
420 41
            if ( ! ($entity instanceof $class->name)) {
0 ignored issues
show
Bug introduced by
Accessing name 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...
421 1
                return null;
422
            }
423
424
            switch ($lockMode) {
425 40
                case LockMode::OPTIMISTIC:
426 1
                    $this->lock($entity, $lockMode, $lockVersion);
427
                    break;
428
429 40
                case LockMode::NONE:
430
                case LockMode::PESSIMISTIC_READ:
431
                case LockMode::PESSIMISTIC_WRITE:
432 40
                    $persister = $unitOfWork->getEntityPersister($class->name);
0 ignored issues
show
Bug introduced by
Accessing name 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...
433 40
                    $persister->refresh($sortedId, $entity, $lockMode);
434 40
                    break;
435
            }
436
437 40
            return $entity; // Hit!
438
        }
439
440 391
        $persister = $unitOfWork->getEntityPersister($class->name);
0 ignored issues
show
Bug introduced by
Accessing name 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...
441
442
        switch ($lockMode) {
443 391
            case LockMode::OPTIMISTIC:
444 1
                if ( ! $class->isVersioned) {
0 ignored issues
show
Bug introduced by
Accessing isVersioned 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...
445 1
                    throw OptimisticLockException::notVersioned($class->name);
0 ignored issues
show
Bug introduced by
Accessing name 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...
446
                }
447
448
                $entity = $persister->load($sortedId);
449
450
                $unitOfWork->lock($entity, $lockMode, $lockVersion);
0 ignored issues
show
Bug introduced by
It seems like $entity defined by $persister->load($sortedId) on line 448 can also be of type null; however, Doctrine\ORM\UnitOfWork::lock() does only seem to accept object, 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...
451
452
                return $entity;
453
454 390
            case LockMode::PESSIMISTIC_READ:
455 389
            case LockMode::PESSIMISTIC_WRITE:
456 2
                if ( ! $this->getConnection()->isTransactionActive()) {
457 2
                    throw TransactionRequiredException::transactionRequired();
458
                }
459
460
                return $persister->load($sortedId, null, null, array(), $lockMode);
461
462
            default:
463 388
                return $persister->loadById($sortedId);
464
        }
465
    }
466
467
    /**
468
     * {@inheritDoc}
469
     */
470 90
    public function getReference($entityName, $id)
471
    {
472 90
        $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
473
474 90
        if ( ! is_array($id)) {
475 49
            $id = array($class->identifier[0] => $id);
0 ignored issues
show
Bug introduced by
Accessing identifier 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...
476
        }
477
478 90
        $sortedId = array();
479
480 90
        foreach ($class->identifier as $identifier) {
0 ignored issues
show
Bug introduced by
Accessing identifier 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...
481 90
            if ( ! isset($id[$identifier])) {
482
                throw ORMException::missingIdentifierField($class->name, $identifier);
0 ignored issues
show
Bug introduced by
Accessing name 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...
483
            }
484
485 90
            $sortedId[$identifier] = $id[$identifier];
486 90
            unset($id[$identifier]);
487
        }
488
489 90
        if ($id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
490 1
            throw ORMException::unrecognizedIdentifierFields($class->name, array_keys($id));
0 ignored issues
show
Bug introduced by
Accessing name 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...
491
        }
492
493
        // Check identity map first, if its already in there just return it.
494 89
        if (($entity = $this->unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) {
0 ignored issues
show
Bug introduced by
Accessing rootEntityName 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...
495 26
            return ($entity instanceof $class->name) ? $entity : null;
0 ignored issues
show
Bug introduced by
Accessing name 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...
496
        }
497
498 85
        if ($class->subClasses) {
0 ignored issues
show
Bug introduced by
Accessing subClasses 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...
499 2
            return $this->find($entityName, $sortedId);
500
        }
501
502 85
        $entity = $this->proxyFactory->getProxy($class->name, $sortedId);
0 ignored issues
show
Bug introduced by
Accessing name 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...
503
504 85
        $this->unitOfWork->registerManaged($entity, $sortedId, array());
505
506 85
        return $entity;
507
    }
508
509
    /**
510
     * {@inheritDoc}
511
     */
512 4
    public function getPartialReference($entityName, $identifier)
513
    {
514 4
        $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
515
516
        // Check identity map first, if its already in there just return it.
517 4
        if (($entity = $this->unitOfWork->tryGetById($identifier, $class->rootEntityName)) !== false) {
0 ignored issues
show
Bug introduced by
Accessing rootEntityName 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...
518 1
            return ($entity instanceof $class->name) ? $entity : null;
0 ignored issues
show
Bug introduced by
Accessing name 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...
519
        }
520
521 3
        if ( ! is_array($identifier)) {
522 3
            $identifier = array($class->identifier[0] => $identifier);
0 ignored issues
show
Bug introduced by
Accessing identifier 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...
523
        }
524
525 3
        $entity = $class->newInstance();
526
527 3
        $class->setIdentifierValues($entity, $identifier);
528
529 3
        $this->unitOfWork->registerManaged($entity, $identifier, array());
530 3
        $this->unitOfWork->markReadOnly($entity);
531
532 3
        return $entity;
533
    }
534
535
    /**
536
     * Clears the EntityManager. All entities that are currently managed
537
     * by this EntityManager become detached.
538
     *
539
     * @param string|null $entityName if given, only entities of this type will get detached
540
     *
541
     * @return void
542
     */
543 1215
    public function clear($entityName = null)
544
    {
545 1215
        $this->unitOfWork->clear($entityName);
546 1215
    }
547
548
    /**
549
     * {@inheritDoc}
550
     */
551 19
    public function close()
552
    {
553 19
        $this->clear();
554
555 19
        $this->closed = true;
556 19
    }
557
558
    /**
559
     * Tells the EntityManager to make an instance managed and persistent.
560
     *
561
     * The entity will be entered into the database at or before transaction
562
     * commit or as a result of the flush operation.
563
     *
564
     * NOTE: The persist operation always considers entities that are not yet known to
565
     * this EntityManager as NEW. Do not pass detached entities to the persist operation.
566
     *
567
     * @param object $entity The instance to make managed and persistent.
568
     *
569
     * @return void
570
     *
571
     * @throws ORMInvalidArgumentException
572
     * @throws ORMException
573
     */
574 1003
    public function persist($entity)
575
    {
576 1003
        if ( ! is_object($entity)) {
577 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()', $entity);
578
        }
579
580 1002
        $this->errorIfClosed();
581
582 1001
        $this->unitOfWork->persist($entity);
583 1000
    }
584
585
    /**
586
     * Removes an entity instance.
587
     *
588
     * A removed entity will be removed from the database at or before transaction commit
589
     * or as a result of the flush operation.
590
     *
591
     * @param object $entity The entity instance to remove.
592
     *
593
     * @return void
594
     *
595
     * @throws ORMInvalidArgumentException
596
     * @throws ORMException
597
     */
598 50
    public function remove($entity)
599
    {
600 50
        if ( ! is_object($entity)) {
601 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#remove()', $entity);
602
        }
603
604 49
        $this->errorIfClosed();
605
606 48
        $this->unitOfWork->remove($entity);
607 48
    }
608
609
    /**
610
     * Refreshes the persistent state of an entity from the database,
611
     * overriding any local changes that have not yet been persisted.
612
     *
613
     * @param object $entity The entity to refresh.
614
     *
615
     * @return void
616
     *
617
     * @throws ORMInvalidArgumentException
618
     * @throws ORMException
619
     */
620 18
    public function refresh($entity)
621
    {
622 18
        if ( ! is_object($entity)) {
623 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#refresh()', $entity);
624
        }
625
626 17
        $this->errorIfClosed();
627
628 16
        $this->unitOfWork->refresh($entity);
629 16
    }
630
631
    /**
632
     * Detaches an entity from the EntityManager, causing a managed entity to
633
     * become detached.  Unflushed changes made to the entity if any
634
     * (including removal of the entity), will not be synchronized to the database.
635
     * Entities which previously referenced the detached entity will continue to
636
     * reference it.
637
     *
638
     * @param object $entity The entity to detach.
639
     *
640
     * @return void
641
     *
642
     * @throws ORMInvalidArgumentException
643
     */
644 13
    public function detach($entity)
645
    {
646 13
        if ( ! is_object($entity)) {
647 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()', $entity);
648
        }
649
650 12
        $this->unitOfWork->detach($entity);
651 12
    }
652
653
    /**
654
     * Merges the state of a detached entity into the persistence context
655
     * of this EntityManager and returns the managed copy of the entity.
656
     * The entity passed to merge will not become associated/managed with this EntityManager.
657
     *
658
     * @param object $entity The detached entity to merge into the persistence context.
659
     *
660
     * @return object The managed copy of the entity.
661
     *
662
     * @throws ORMInvalidArgumentException
663
     * @throws ORMException
664
     */
665 42
    public function merge($entity)
666
    {
667 42
        if ( ! is_object($entity)) {
668 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()', $entity);
669
        }
670
671 41
        $this->errorIfClosed();
672
673 40
        return $this->unitOfWork->merge($entity);
674
    }
675
676
    /**
677
     * {@inheritDoc}
678
     *
679
     * @todo Implementation need. This is necessary since $e2 = clone $e1; throws an E_FATAL when access anything on $e:
680
     * Fatal error: Maximum function nesting level of '100' reached, aborting!
681
     */
682
    public function copy($entity, $deep = false)
683
    {
684
        throw new \BadMethodCallException("Not implemented.");
685
    }
686
687
    /**
688
     * {@inheritDoc}
689
     */
690 10
    public function lock($entity, $lockMode, $lockVersion = null)
691
    {
692 10
        $this->unitOfWork->lock($entity, $lockMode, $lockVersion);
693 3
    }
694
695
    /**
696
     * Gets the repository for an entity class.
697
     *
698
     * @param string $entityName The name of the entity.
699
     *
700
     * @return \Doctrine\ORM\EntityRepository The repository class.
701
     */
702 144
    public function getRepository($entityName)
703
    {
704 144
        return $this->repositoryFactory->getRepository($this, $entityName);
705
    }
706
707
    /**
708
     * Determines whether an entity instance is managed in this EntityManager.
709
     *
710
     * @param object $entity
711
     *
712
     * @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise.
713
     */
714 22
    public function contains($entity)
715
    {
716 22
        return $this->unitOfWork->isScheduledForInsert($entity)
717 20
            || $this->unitOfWork->isInIdentityMap($entity)
718 22
            && ! $this->unitOfWork->isScheduledForDelete($entity);
719
    }
720
721
    /**
722
     * {@inheritDoc}
723
     */
724 2324
    public function getEventManager()
725
    {
726 2324
        return $this->eventManager;
727
    }
728
729
    /**
730
     * {@inheritDoc}
731
     */
732 2324
    public function getConfiguration()
733
    {
734 2324
        return $this->config;
735
    }
736
737
    /**
738
     * Throws an exception if the EntityManager is closed or currently not active.
739
     *
740
     * @return void
741
     *
742
     * @throws ORMException If the EntityManager is closed.
743
     */
744 1022
    private function errorIfClosed()
745
    {
746 1022
        if ($this->closed) {
747 5
            throw ORMException::entityManagerClosed();
748
        }
749 1017
    }
750
751
    /**
752
     * {@inheritDoc}
753
     */
754 1
    public function isOpen()
755
    {
756 1
        return (!$this->closed);
757
    }
758
759
    /**
760
     * {@inheritDoc}
761
     */
762 2324
    public function getUnitOfWork()
763
    {
764 2324
        return $this->unitOfWork;
765
    }
766
767
    /**
768
     * {@inheritDoc}
769
     */
770
    public function getHydrator($hydrationMode)
771
    {
772
        return $this->newHydrator($hydrationMode);
773
    }
774
775
    /**
776
     * {@inheritDoc}
777
     */
778 889
    public function newHydrator($hydrationMode)
779
    {
780
        switch ($hydrationMode) {
781 889
            case Query::HYDRATE_OBJECT:
782 632
                return new Internal\Hydration\ObjectHydrator($this);
783
784 535
            case Query::HYDRATE_ARRAY:
785 35
                return new Internal\Hydration\ArrayHydrator($this);
786
787 505
            case Query::HYDRATE_SCALAR:
788 85
                return new Internal\Hydration\ScalarHydrator($this);
789
790 422
            case Query::HYDRATE_SINGLE_SCALAR:
791 12
                return new Internal\Hydration\SingleScalarHydrator($this);
792
793 414
            case Query::HYDRATE_SIMPLEOBJECT:
794 413
                return new Internal\Hydration\SimpleObjectHydrator($this);
795
796
            default:
797 1
                if (($class = $this->config->getCustomHydrationMode($hydrationMode)) !== null) {
798 1
                    return new $class($this);
799
                }
800
        }
801
802
        throw ORMException::invalidHydrationMode($hydrationMode);
803
    }
804
805
    /**
806
     * {@inheritDoc}
807
     */
808 165
    public function getProxyFactory()
809
    {
810 165
        return $this->proxyFactory;
811
    }
812
813
    /**
814
     * {@inheritDoc}
815
     */
816
    public function initializeObject($obj)
817
    {
818
        $this->unitOfWork->initializeObject($obj);
819
    }
820
821
    /**
822
     * Factory method to create EntityManager instances.
823
     *
824
     * @param array|Connection $connection   An array with the connection parameters or an existing Connection instance.
825
     * @param Configuration    $config       The Configuration instance to use.
826
     * @param EventManager     $eventManager The EventManager instance to use.
827
     *
828
     * @return EntityManager The created EntityManager.
829
     *
830
     * @throws \InvalidArgumentException
831
     * @throws ORMException
832
     */
833 1227
    public static function create($connection, Configuration $config, EventManager $eventManager = null)
834
    {
835 1227
        if ( ! $config->getMetadataDriverImpl()) {
836
            throw ORMException::missingMappingDriverImpl();
837
        }
838
839 1227
        $connection = static::createConnection($connection, $config, $eventManager);
840
841 1227
        return new EntityManager($connection, $config, $connection->getEventManager());
842
    }
843
844
    /**
845
     * Factory method to create Connection instances.
846
     *
847
     * @param array|Connection $connection   An array with the connection parameters or an existing Connection instance.
848
     * @param Configuration    $config       The Configuration instance to use.
849
     * @param EventManager     $eventManager The EventManager instance to use.
850
     *
851
     * @return Connection
852
     *
853
     * @throws \InvalidArgumentException
854
     * @throws ORMException
855
     */
856 1227
    protected static function createConnection($connection, Configuration $config, EventManager $eventManager = null)
857
    {
858 1227
        if (is_array($connection)) {
859
            return DriverManager::getConnection($connection, $config, $eventManager ?: new EventManager());
860
        }
861
862 1227
        if ( ! $connection instanceof Connection) {
863
            throw new \InvalidArgumentException("Invalid argument: " . $connection);
864
        }
865
866 1227
        if ($eventManager !== null && $connection->getEventManager() !== $eventManager) {
867
            throw ORMException::mismatchedEventManager();
868
        }
869
870 1227
        return $connection;
871
    }
872
873
    /**
874
     * {@inheritDoc}
875
     */
876 613
    public function getFilters()
877
    {
878 613
        if (null === $this->filterCollection) {
879 613
            $this->filterCollection = new FilterCollection($this);
880
        }
881
882 613
        return $this->filterCollection;
883
    }
884
885
    /**
886
     * {@inheritDoc}
887
     */
888 35
    public function isFiltersStateClean()
889
    {
890 35
        return null === $this->filterCollection || $this->filterCollection->isClean();
891
    }
892
893
    /**
894
     * {@inheritDoc}
895
     */
896 732
    public function hasFilters()
897
    {
898 732
        return null !== $this->filterCollection;
899
    }
900
}
901