Completed
Pull Request — master (#5806)
by Adelar
12:07
created

EntityManager::flush()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
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\LockMode;
26
use Doctrine\ORM\Query\ResultSetMapping;
27
use Doctrine\ORM\Proxy\ProxyFactory;
28
use Doctrine\ORM\Query\FilterCollection;
29
use Doctrine\Common\Util\ClassUtils;
30
31
/**
32
 * The EntityManager is the central access point to ORM functionality.
33
 *
34
 * It is a facade to all different ORM subsystems such as UnitOfWork,
35
 * Query Language and Repository API. Instantiation is done through
36
 * the static create() method. The quickest way to obtain a fully
37
 * configured EntityManager is:
38
 *
39
 *     use Doctrine\ORM\Tools\Setup;
40
 *     use Doctrine\ORM\EntityManager;
41
 *
42
 *     $paths = array('/path/to/entity/mapping/files');
43
 *
44
 *     $config = Setup::createAnnotationMetadataConfiguration($paths);
45
 *     $dbParams = array('driver' => 'pdo_sqlite', 'memory' => true);
46
 *     $entityManager = EntityManager::create($dbParams, $config);
47
 *
48
 * For more information see
49
 * {@link http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/configuration.html}
50
 *
51
 * You should never attempt to inherit from the EntityManager: Inheritance
52
 * is not a valid extension point for the EntityManager. Instead you
53
 * should take a look at the {@see \Doctrine\ORM\Decorator\EntityManagerDecorator}
54
 * and wrap your entity manager in a decorator.
55
 *
56
 * @since   2.0
57
 * @author  Benjamin Eberlei <[email protected]>
58
 * @author  Guilherme Blanco <[email protected]>
59
 * @author  Jonathan Wage <[email protected]>
60
 * @author  Roman Borschel <[email protected]>
61
 */
62
/* final */class EntityManager implements EntityManagerInterface
63
{
64
    /**
65
     * The used Configuration.
66
     *
67
     * @var \Doctrine\ORM\Configuration
68
     */
69
    private $config;
70
71
    /**
72
     * The database connection used by the EntityManager.
73
     *
74
     * @var \Doctrine\DBAL\Connection
75
     */
76
    private $conn;
77
78
    /**
79
     * The metadata factory, used to retrieve the ORM metadata of entity classes.
80
     *
81
     * @var \Doctrine\ORM\Mapping\ClassMetadataFactory
82
     */
83
    private $metadataFactory;
84
85
    /**
86
     * The UnitOfWork used to coordinate object-level transactions.
87
     *
88
     * @var \Doctrine\ORM\UnitOfWork
89
     */
90
    private $unitOfWork;
91
92
    /**
93
     * The event manager that is the central point of the event system.
94
     *
95
     * @var \Doctrine\Common\EventManager
96
     */
97
    private $eventManager;
98
99
    /**
100
     * The proxy factory used to create dynamic proxies.
101
     *
102
     * @var \Doctrine\ORM\Proxy\ProxyFactory
103
     */
104
    private $proxyFactory;
105
106
    /**
107
     * The repository factory used to create dynamic repositories.
108
     *
109
     * @var \Doctrine\ORM\Repository\RepositoryFactory
110
     */
111
    private $repositoryFactory;
112
113
    /**
114
     * The expression builder instance used to generate query expressions.
115
     *
116
     * @var \Doctrine\ORM\Query\Expr
117
     */
118
    private $expressionBuilder;
119
120
    /**
121
     * Whether the EntityManager is closed or not.
122
     *
123
     * @var bool
124
     */
125
    private $closed = false;
126
127
    /**
128
     * Collection of query filters.
129
     *
130
     * @var \Doctrine\ORM\Query\FilterCollection
131
     */
132
    private $filterCollection;
133
134
    /**
135
     * @var \Doctrine\ORM\Cache The second level cache regions API.
136
     */
137
    private $cache;
138
139
    /**
140
     * Creates a new EntityManager that operates on the given database connection
141
     * and uses the given Configuration and EventManager implementations.
142
     *
143
     * @param \Doctrine\DBAL\Connection     $conn
144
     * @param \Doctrine\ORM\Configuration   $config
145
     * @param \Doctrine\Common\EventManager $eventManager
146
     */
147 2323
    protected function __construct(Connection $conn, Configuration $config, EventManager $eventManager)
148
    {
149 2323
        $this->conn              = $conn;
150 2323
        $this->config            = $config;
151 2323
        $this->eventManager      = $eventManager;
152
153 2323
        $metadataFactoryClassName = $config->getClassMetadataFactoryName();
154
155 2323
        $this->metadataFactory = new $metadataFactoryClassName;
156 2323
        $this->metadataFactory->setEntityManager($this);
157 2323
        $this->metadataFactory->setCacheDriver($this->config->getMetadataCacheImpl());
158
159 2323
        $this->repositoryFactory = $config->getRepositoryFactory();
160 2323
        $this->unitOfWork        = new UnitOfWork($this);
161 2323
        $this->proxyFactory      = new ProxyFactory(
162
            $this,
163 2323
            $config->getProxyDir(),
164 2323
            $config->getProxyNamespace(),
165 2323
            $config->getAutoGenerateProxyClasses()
166
        );
167
168 2323
        if ($config->isSecondLevelCacheEnabled()) {
169 275
            $cacheConfig    = $config->getSecondLevelCacheConfiguration();
170 275
            $cacheFactory   = $cacheConfig->getCacheFactory();
171 275
            $this->cache    = $cacheFactory->createCache($this);
172
        }
173 2323
    }
174
175
    /**
176
     * {@inheritDoc}
177
     */
178 1827
    public function getConnection()
179
    {
180 1827
        return $this->conn;
181
    }
182
183
    /**
184
     * Gets the metadata factory used to gather the metadata of classes.
185
     *
186
     * @return \Doctrine\ORM\Mapping\ClassMetadataFactory
187
     */
188 2323
    public function getMetadataFactory()
189
    {
190 2323
        return $this->metadataFactory;
191
    }
192
193
    /**
194
     * {@inheritDoc}
195
     */
196 17
    public function getExpressionBuilder()
197
    {
198 17
        if ($this->expressionBuilder === null) {
199 17
            $this->expressionBuilder = new Query\Expr;
200
        }
201
202 17
        return $this->expressionBuilder;
203
    }
204
205
    /**
206
     * {@inheritDoc}
207
     */
208 2
    public function beginTransaction()
209
    {
210 2
        $this->conn->beginTransaction();
211 2
    }
212
213
    /**
214
     * {@inheritDoc}
215
     */
216 210
    public function getCache()
217
    {
218 210
        return $this->cache;
219
    }
220
221
    /**
222
     * {@inheritDoc}
223
     */
224 4
    public function transactional($func)
225
    {
226 4
        if (!is_callable($func)) {
227 1
            throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"');
228
        }
229
230 3
        $this->conn->beginTransaction();
231
232
        try {
233 3
            $return = call_user_func($func, $this);
234
235 3
            $this->flush();
236 3
            $this->conn->commit();
237
238 3
            return $return ?: true;
239
        } catch (Exception $e) {
240
            $this->close();
241
            $this->conn->rollBack();
242
243
            throw $e;
244
        }
245
    }
246
247
    /**
248
     * {@inheritDoc}
249
     */
250 1
    public function commit()
251
    {
252 1
        $this->conn->commit();
253 1
    }
254
255
    /**
256
     * {@inheritDoc}
257
     */
258 1
    public function rollback()
259
    {
260 1
        $this->conn->rollBack();
261 1
    }
262
263
    /**
264
     * Returns the ORM metadata descriptor for a class.
265
     *
266
     * The class name must be the fully-qualified class name without a leading backslash
267
     * (as it is returned by get_class($obj)) or an aliased class name.
268
     *
269
     * Examples:
270
     * MyProject\Domain\User
271
     * sales:PriceRequest
272
     *
273
     * Internal note: Performance-sensitive method.
274
     *
275
     * @param string $className
276
     *
277
     * @return \Doctrine\ORM\Mapping\ClassMetadata
278
     */
279 1880
    public function getClassMetadata($className)
280
    {
281 1880
        return $this->metadataFactory->getMetadataFor($className);
282
    }
283
284
    /**
285
     * {@inheritDoc}
286
     */
287 922
    public function createQuery($dql = '')
288
    {
289 922
        $query = new Query($this);
290
291 922
        if ( ! empty($dql)) {
292 917
            $query->setDql($dql);
293
        }
294
295 922
        return $query;
296
    }
297
298
    /**
299
     * {@inheritDoc}
300
     */
301 1
    public function createNamedQuery($name)
302
    {
303 1
        return $this->createQuery($this->config->getNamedQuery($name));
304
    }
305
306
    /**
307
     * {@inheritDoc}
308
     */
309 21
    public function createNativeQuery($sql, ResultSetMapping $rsm)
310
    {
311 21
        $query = new NativeQuery($this);
312
313 21
        $query->setSql($sql);
314 21
        $query->setResultSetMapping($rsm);
315
316 21
        return $query;
317
    }
318
319
    /**
320
     * {@inheritDoc}
321
     */
322 1
    public function createNamedNativeQuery($name)
323
    {
324 1
        list($sql, $rsm) = $this->config->getNamedNativeQuery($name);
325
326 1
        return $this->createNativeQuery($sql, $rsm);
327
    }
328
329
    /**
330
     * {@inheritDoc}
331
     */
332 112
    public function createQueryBuilder()
333
    {
334 112
        return new QueryBuilder($this);
335
    }
336
337
    /**
338
     * Flushes all changes to objects that have been queued up to now to the database.
339
     * This effectively synchronizes the in-memory state of managed objects with the
340
     * database.
341
     *
342
     * If an entity is explicitly passed to this method only this entity and
343
     * the cascade-persist semantics + scheduled inserts/removals are synchronized.
344
     *
345
     * @param null|object|array $entity
346
     *
347
     * @return void
348
     *
349
     * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that
350
     *         makes use of optimistic locking fails.
351
     * @throws ORMException
352
     */
353 1009
    public function flush($entity = null)
354
    {
355 1009
        $this->errorIfClosed();
356
357 1008
        $this->unitOfWork->commit($entity);
358 999
    }
359
360
    /**
361
     * Finds an Entity by its identifier.
362
     *
363
     * @param string       $entityName  The class name of the entity to find.
364
     * @param mixed        $id          The identity of the entity to find.
365
     * @param integer|null $lockMode    One of the \Doctrine\DBAL\LockMode::* constants
366
     *                                  or NULL if no specific lock mode should be used
367
     *                                  during the search.
368
     * @param integer|null $lockVersion The version of the entity to find when using
369
     *                                  optimistic locking.
370
     *
371
     * @return object|null The entity instance or NULL if the entity can not be found.
372
     *
373
     * @throws OptimisticLockException
374
     * @throws ORMInvalidArgumentException
375
     * @throws TransactionRequiredException
376
     * @throws ORMException
377
     */
378 409
    public function find($entityName, $id, $lockMode = null, $lockVersion = null)
379
    {
380 409
        $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
381
382 409
        if ( ! is_array($id)) {
383 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...
384
                throw ORMInvalidArgumentException::invalidCompositeIdentifier();
385
            }
386
387 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...
388
        }
389
390 409
        foreach ($id as $i => $value) {
391 409
            if (is_object($value) && $this->metadataFactory->hasMetadataFor(ClassUtils::getClass($value))) {
392 6
                $id[$i] = $this->unitOfWork->getSingleIdentifierValue($value);
393
394 6
                if ($id[$i] === null) {
395 409
                    throw ORMInvalidArgumentException::invalidIdentifierBindingEntity();
396
                }
397
            }
398
        }
399
400 408
        $sortedId = array();
401
402 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...
403 408
            if ( ! isset($id[$identifier])) {
404 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...
405
            }
406
407 407
            $sortedId[$identifier] = $id[$identifier];
408 407
            unset($id[$identifier]);
409
        }
410
411 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...
412 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...
413
        }
414
415 406
        $unitOfWork = $this->getUnitOfWork();
416
417
        // Check identity map first
418 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...
419 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...
420 1
                return null;
421
            }
422
423
            switch (true) {
424 40
                case LockMode::OPTIMISTIC === $lockMode:
425 1
                    $this->lock($entity, $lockMode, $lockVersion);
426
                    break;
427
428 40
                case LockMode::NONE === $lockMode:
429 40
                case LockMode::PESSIMISTIC_READ === $lockMode:
430 40
                case LockMode::PESSIMISTIC_WRITE === $lockMode:
431
                    $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...
432
                    $persister->refresh($sortedId, $entity, $lockMode);
433
                    break;
434
            }
435
436 40
            return $entity; // Hit!
437
        }
438
439 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...
440
441
        switch (true) {
442 391
            case LockMode::OPTIMISTIC === $lockMode:
443 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...
444 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...
445
                }
446
447
                $entity = $persister->load($sortedId);
448
449
                $unitOfWork->lock($entity, $lockMode, $lockVersion);
0 ignored issues
show
Bug introduced by
It seems like $entity defined by $persister->load($sortedId) on line 447 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...
450
451
                return $entity;
452
453 390
            case LockMode::PESSIMISTIC_READ === $lockMode:
454 389
            case LockMode::PESSIMISTIC_WRITE === $lockMode:
455 2
                if ( ! $this->getConnection()->isTransactionActive()) {
456 2
                    throw TransactionRequiredException::transactionRequired();
457
                }
458
                return $persister->load($sortedId, null, null, array(), $lockMode);
459
460 388
            case LockMode::NONE === $lockMode:
461
                return $persister->load($sortedId, null, null, array(), $lockMode);
462
463
            default:
464 388
                return $persister->loadById($sortedId);
465
        }
466
    }
467
468
    /**
469
     * {@inheritDoc}
470
     */
471 90
    public function getReference($entityName, $id)
472
    {
473 90
        $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
474
475 90
        if ( ! is_array($id)) {
476 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...
477
        }
478
479 90
        $sortedId = array();
480
481 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...
482 90
            if ( ! isset($id[$identifier])) {
483
                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...
484
            }
485
486 90
            $sortedId[$identifier] = $id[$identifier];
487 90
            unset($id[$identifier]);
488
        }
489
490 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...
491 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...
492
        }
493
494
        // Check identity map first, if its already in there just return it.
495 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...
496 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...
497
        }
498
499 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...
500 2
            return $this->find($entityName, $sortedId);
501
        }
502
503 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...
504
505 85
        $this->unitOfWork->registerManaged($entity, $sortedId, array());
506
507 85
        return $entity;
508
    }
509
510
    /**
511
     * {@inheritDoc}
512
     */
513 4
    public function getPartialReference($entityName, $identifier)
514
    {
515 4
        $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
516
517
        // Check identity map first, if its already in there just return it.
518 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...
519 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...
520
        }
521
522 3
        if ( ! is_array($identifier)) {
523 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...
524
        }
525
526 3
        $entity = $class->newInstance();
527
528 3
        $class->setIdentifierValues($entity, $identifier);
529
530 3
        $this->unitOfWork->registerManaged($entity, $identifier, array());
531 3
        $this->unitOfWork->markReadOnly($entity);
532
533 3
        return $entity;
534
    }
535
536
    /**
537
     * Clears the EntityManager. All entities that are currently managed
538
     * by this EntityManager become detached.
539
     *
540
     * @param string|null $entityName if given, only entities of this type will get detached
541
     *
542
     * @return void
543
     */
544 1215
    public function clear($entityName = null)
545
    {
546 1215
        $this->unitOfWork->clear($entityName);
547 1215
    }
548
549
    /**
550
     * {@inheritDoc}
551
     */
552 19
    public function close()
553
    {
554 19
        $this->clear();
555
556 19
        $this->closed = true;
557 19
    }
558
559
    /**
560
     * Tells the EntityManager to make an instance managed and persistent.
561
     *
562
     * The entity will be entered into the database at or before transaction
563
     * commit or as a result of the flush operation.
564
     *
565
     * NOTE: The persist operation always considers entities that are not yet known to
566
     * this EntityManager as NEW. Do not pass detached entities to the persist operation.
567
     *
568
     * @param object $entity The instance to make managed and persistent.
569
     *
570
     * @return void
571
     *
572
     * @throws ORMInvalidArgumentException
573
     * @throws ORMException
574
     */
575 1003
    public function persist($entity)
576
    {
577 1003
        if ( ! is_object($entity)) {
578 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()', $entity);
579
        }
580
581 1002
        $this->errorIfClosed();
582
583 1001
        $this->unitOfWork->persist($entity);
584 1000
    }
585
586
    /**
587
     * Removes an entity instance.
588
     *
589
     * A removed entity will be removed from the database at or before transaction commit
590
     * or as a result of the flush operation.
591
     *
592
     * @param object $entity The entity instance to remove.
593
     *
594
     * @return void
595
     *
596
     * @throws ORMInvalidArgumentException
597
     * @throws ORMException
598
     */
599 51
    public function remove($entity)
600
    {
601 51
        if ( ! is_object($entity)) {
602 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#remove()', $entity);
603
        }
604
605 50
        $this->errorIfClosed();
606
607 49
        $this->unitOfWork->remove($entity);
608 49
    }
609
610
    /**
611
     * Refreshes the persistent state of an entity from the database,
612
     * overriding any local changes that have not yet been persisted.
613
     *
614
     * @param object $entity The entity to refresh.
615
     *
616
     * @return void
617
     *
618
     * @throws ORMInvalidArgumentException
619
     * @throws ORMException
620
     */
621 19
    public function refresh($entity)
622
    {
623 19
        if ( ! is_object($entity)) {
624 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#refresh()', $entity);
625
        }
626
627 18
        $this->errorIfClosed();
628
629 17
        $this->unitOfWork->refresh($entity);
630 17
    }
631
632
    /**
633
     * Detaches an entity from the EntityManager, causing a managed entity to
634
     * become detached.  Unflushed changes made to the entity if any
635
     * (including removal of the entity), will not be synchronized to the database.
636
     * Entities which previously referenced the detached entity will continue to
637
     * reference it.
638
     *
639
     * @param object $entity The entity to detach.
640
     *
641
     * @return void
642
     *
643
     * @throws ORMInvalidArgumentException
644
     */
645 13
    public function detach($entity)
646
    {
647 13
        if ( ! is_object($entity)) {
648 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()', $entity);
649
        }
650
651 12
        $this->unitOfWork->detach($entity);
652 12
    }
653
654
    /**
655
     * Merges the state of a detached entity into the persistence context
656
     * of this EntityManager and returns the managed copy of the entity.
657
     * The entity passed to merge will not become associated/managed with this EntityManager.
658
     *
659
     * @param object $entity The detached entity to merge into the persistence context.
660
     *
661
     * @return object The managed copy of the entity.
662
     *
663
     * @throws ORMInvalidArgumentException
664
     * @throws ORMException
665
     */
666 42
    public function merge($entity)
667
    {
668 42
        if ( ! is_object($entity)) {
669 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()', $entity);
670
        }
671
672 41
        $this->errorIfClosed();
673
674 40
        return $this->unitOfWork->merge($entity);
675
    }
676
677
    /**
678
     * {@inheritDoc}
679
     *
680
     * @todo Implementation need. This is necessary since $e2 = clone $e1; throws an E_FATAL when access anything on $e:
681
     * Fatal error: Maximum function nesting level of '100' reached, aborting!
682
     */
683
    public function copy($entity, $deep = false)
684
    {
685
        throw new \BadMethodCallException("Not implemented.");
686
    }
687
688
    /**
689
     * {@inheritDoc}
690
     */
691 10
    public function lock($entity, $lockMode, $lockVersion = null)
692
    {
693 10
        $this->unitOfWork->lock($entity, $lockMode, $lockVersion);
694 3
    }
695
696
    /**
697
     * Gets the repository for an entity class.
698
     *
699
     * @param string $entityName The name of the entity.
700
     *
701
     * @return \Doctrine\ORM\EntityRepository The repository class.
702
     */
703 144
    public function getRepository($entityName)
704
    {
705 144
        return $this->repositoryFactory->getRepository($this, $entityName);
706
    }
707
708
    /**
709
     * Determines whether an entity instance is managed in this EntityManager.
710
     *
711
     * @param object $entity
712
     *
713
     * @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise.
714
     */
715 22
    public function contains($entity)
716
    {
717 22
        return $this->unitOfWork->isScheduledForInsert($entity)
718 20
            || $this->unitOfWork->isInIdentityMap($entity)
719 22
            && ! $this->unitOfWork->isScheduledForDelete($entity);
720
    }
721
722
    /**
723
     * {@inheritDoc}
724
     */
725 2323
    public function getEventManager()
726
    {
727 2323
        return $this->eventManager;
728
    }
729
730
    /**
731
     * {@inheritDoc}
732
     */
733 2323
    public function getConfiguration()
734
    {
735 2323
        return $this->config;
736
    }
737
738
    /**
739
     * Throws an exception if the EntityManager is closed or currently not active.
740
     *
741
     * @return void
742
     *
743
     * @throws ORMException If the EntityManager is closed.
744
     */
745 1022
    private function errorIfClosed()
746
    {
747 1022
        if ($this->closed) {
748 5
            throw ORMException::entityManagerClosed();
749
        }
750 1017
    }
751
752
    /**
753
     * {@inheritDoc}
754
     */
755 1
    public function isOpen()
756
    {
757 1
        return (!$this->closed);
758
    }
759
760
    /**
761
     * {@inheritDoc}
762
     */
763 2323
    public function getUnitOfWork()
764
    {
765 2323
        return $this->unitOfWork;
766
    }
767
768
    /**
769
     * {@inheritDoc}
770
     */
771
    public function getHydrator($hydrationMode)
772
    {
773
        return $this->newHydrator($hydrationMode);
774
    }
775
776
    /**
777
     * {@inheritDoc}
778
     */
779 881
    public function newHydrator($hydrationMode)
780
    {
781
        switch ($hydrationMode) {
782 881
            case Query::HYDRATE_OBJECT:
783 614
                return new Internal\Hydration\ObjectHydrator($this);
784
785 536
            case Query::HYDRATE_ARRAY:
786 35
                return new Internal\Hydration\ArrayHydrator($this);
787
788 506
            case Query::HYDRATE_SCALAR:
789 85
                return new Internal\Hydration\ScalarHydrator($this);
790
791 423
            case Query::HYDRATE_SINGLE_SCALAR:
792 12
                return new Internal\Hydration\SingleScalarHydrator($this);
793
794 415
            case Query::HYDRATE_SIMPLEOBJECT:
795 414
                return new Internal\Hydration\SimpleObjectHydrator($this);
796
797
            default:
798 1
                if (($class = $this->config->getCustomHydrationMode($hydrationMode)) !== null) {
799 1
                    return new $class($this);
800
                }
801
        }
802
803
        throw ORMException::invalidHydrationMode($hydrationMode);
804
    }
805
806
    /**
807
     * {@inheritDoc}
808
     */
809 165
    public function getProxyFactory()
810
    {
811 165
        return $this->proxyFactory;
812
    }
813
814
    /**
815
     * {@inheritDoc}
816
     */
817
    public function initializeObject($obj)
818
    {
819
        $this->unitOfWork->initializeObject($obj);
820
    }
821
822
    /**
823
     * Factory method to create EntityManager instances.
824
     *
825
     * @param mixed         $conn         An array with the connection parameters or an existing Connection instance.
826
     * @param Configuration $config       The Configuration instance to use.
827
     * @param EventManager  $eventManager The EventManager instance to use.
828
     *
829
     * @return EntityManager The created EntityManager.
830
     *
831
     * @throws \InvalidArgumentException
832
     * @throws ORMException
833
     */
834 1227
    public static function create($conn, Configuration $config, EventManager $eventManager = null)
835
    {
836 1227
        if ( ! $config->getMetadataDriverImpl()) {
837
            throw ORMException::missingMappingDriverImpl();
838
        }
839
840
        switch (true) {
841 1227
            case (is_array($conn)):
842
                $conn = \Doctrine\DBAL\DriverManager::getConnection(
843
                    $conn, $config, ($eventManager ?: new EventManager())
844
                );
845
                break;
846
847
            case ($conn instanceof Connection):
848 1227
                if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
849
                     throw ORMException::mismatchedEventManager();
850
                }
851 1227
                break;
852
853
            default:
854
                throw new \InvalidArgumentException("Invalid argument: " . $conn);
855
        }
856
857 1227
        return new EntityManager($conn, $config, $conn->getEventManager());
858
    }
859
860
    /**
861
     * {@inheritDoc}
862
     */
863 604
    public function getFilters()
864
    {
865 604
        if (null === $this->filterCollection) {
866 604
            $this->filterCollection = new FilterCollection($this);
867
        }
868
869 604
        return $this->filterCollection;
870
    }
871
872
    /**
873
     * {@inheritDoc}
874
     */
875 35
    public function isFiltersStateClean()
876
    {
877 35
        return null === $this->filterCollection || $this->filterCollection->isClean();
878
    }
879
880
    /**
881
     * {@inheritDoc}
882
     */
883 733
    public function hasFilters()
884
    {
885 733
        return null !== $this->filterCollection;
886
    }
887
}
888