Failed Conditions
Pull Request — 2.7 (#7556)
by
unknown
13:39
created

EntityManager::errorIfClosed()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

445
                    $persister->refresh($sortedId, /** @scrutinizer ignore-type */ $entity, $lockMode);
Loading history...
446
                    break;
447
            }
448
449 48
            return $entity; // Hit!
0 ignored issues
show
Bug Best Practice introduced by
The expression return $entity also could return the type true which is incompatible with the documented return type null|object.
Loading history...
450
        }
451
452 415
        $persister = $unitOfWork->getEntityPersister($class->name);
453
454
        switch (true) {
455 415
            case LockMode::OPTIMISTIC === $lockMode:
456 1
                $entity = $persister->load($sortedId);
457
458 1
                $unitOfWork->lock($entity, $lockMode, $lockVersion);
459
460 1
                return $entity;
461
462 414
            case LockMode::PESSIMISTIC_READ === $lockMode:
463 414
            case LockMode::PESSIMISTIC_WRITE === $lockMode:
464
                return $persister->load($sortedId, null, null, [], $lockMode);
465
466
            default:
467 414
                return $persister->loadById($sortedId);
468
        }
469
    }
470
471
    /**
472
     * {@inheritDoc}
473
     */
474 94
    public function getReference($entityName, $id)
475
    {
476 94
        $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
477
478 94
        if ( ! is_array($id)) {
479 50
            $id = [$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?
Loading history...
480
        }
481
482 94
        $sortedId = [];
483
484 94
        foreach ($class->identifier as $identifier) {
485 94
            if ( ! isset($id[$identifier])) {
486
                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?
Loading history...
487
            }
488
489 94
            $sortedId[$identifier] = $id[$identifier];
490 94
            unset($id[$identifier]);
491
        }
492
493 94
        if ($id) {
494 1
            throw ORMException::unrecognizedIdentifierFields($class->name, array_keys($id));
495
        }
496
497
        // Check identity map first, if its already in there just return it.
498 93
        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?
Loading history...
499 28
            return ($entity instanceof $class->name) ? $entity : null;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $entity instanceo...->name ? $entity : null also could return the type true which is incompatible with the return type mandated by Doctrine\ORM\EntityManag...terface::getReference() of null|object.
Loading history...
500
        }
501
502 88
        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?
Loading history...
503 2
            return $this->find($entityName, $sortedId);
504
        }
505
506 88
        $entity = $this->proxyFactory->getProxy($class->name, $sortedId);
507
508 88
        $this->unitOfWork->registerManaged($entity, $sortedId, []);
509
510 88
        return $entity;
511
    }
512
513
    /**
514
     * {@inheritDoc}
515
     */
516 4
    public function getPartialReference($entityName, $identifier)
517
    {
518 4
        $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
519
520
        // Check identity map first, if its already in there just return it.
521 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?
Loading history...
522 1
            return ($entity instanceof $class->name) ? $entity : null;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $entity instanceo...->name ? $entity : null also could return the type true which is incompatible with the return type mandated by Doctrine\ORM\EntityManag...::getPartialReference() of null|object.
Loading history...
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?
Loading history...
523
        }
524
525 3
        if ( ! is_array($identifier)) {
526 3
            $identifier = [$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?
Loading history...
527
        }
528
529 3
        $entity = $class->newInstance();
530
531 3
        $class->setIdentifierValues($entity, $identifier);
532
533 3
        $this->unitOfWork->registerManaged($entity, $identifier, []);
534 3
        $this->unitOfWork->markReadOnly($entity);
535
536 3
        return $entity;
537
    }
538
539
    /**
540
     * Clears the EntityManager. All entities that are currently managed
541
     * by this EntityManager become detached.
542
     *
543
     * @param string|null $entityName if given, only entities of this type will get detached
544
     *
545
     * @return void
546
     *
547
     * @throws ORMInvalidArgumentException                           if a non-null non-string value is given
548
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException if a $entityName is given, but that entity is not
549
     *                                                               found in the mappings
550
     */
551 1305
    public function clear($entityName = null)
552
    {
553 1305
        if (null !== $entityName && ! is_string($entityName)) {
0 ignored issues
show
introduced by
The condition is_string($entityName) is always true.
Loading history...
554 1
            throw ORMInvalidArgumentException::invalidEntityName($entityName);
555
        }
556
557 1304
        $this->unitOfWork->clear(
558 1304
            null === $entityName
559 1302
                ? null
560 1304
                : $this->metadataFactory->getMetadataFor($entityName)->getName()
561
        );
562 1303
    }
563
564
    /**
565
     * {@inheritDoc}
566
     */
567 20
    public function close()
568
    {
569 20
        $this->clear();
570
571 20
        $this->closed = true;
572 20
    }
573
574
    /**
575
     * Tells the EntityManager to make an instance managed and persistent.
576
     *
577
     * The entity will be entered into the database at or before transaction
578
     * commit or as a result of the flush operation.
579
     *
580
     * NOTE: The persist operation always considers entities that are not yet known to
581
     * this EntityManager as NEW. Do not pass detached entities to the persist operation.
582
     *
583
     * @param object $entity The instance to make managed and persistent.
584
     *
585
     * @return void
586
     *
587
     * @throws ORMInvalidArgumentException
588
     * @throws ORMException
589
     */
590 1074
    public function persist($entity)
591
    {
592 1074
        if ( ! is_object($entity)) {
593 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()', $entity);
594
        }
595
596 1073
        $this->errorIfClosed();
597
598 1072
        $this->unitOfWork->persist($entity);
599 1071
    }
600
601
    /**
602
     * Removes an entity instance.
603
     *
604
     * A removed entity will be removed from the database at or before transaction commit
605
     * or as a result of the flush operation.
606
     *
607
     * @param object $entity The entity instance to remove.
608
     *
609
     * @return void
610
     *
611
     * @throws ORMInvalidArgumentException
612
     * @throws ORMException
613
     */
614 52
    public function remove($entity)
615
    {
616 52
        if ( ! is_object($entity)) {
617 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#remove()', $entity);
618
        }
619
620 51
        $this->errorIfClosed();
621
622 50
        $this->unitOfWork->remove($entity);
623 50
    }
624
625
    /**
626
     * Refreshes the persistent state of an entity from the database,
627
     * overriding any local changes that have not yet been persisted.
628
     *
629
     * @param object $entity The entity to refresh.
630
     *
631
     * @return void
632
     *
633
     * @throws ORMInvalidArgumentException
634
     * @throws ORMException
635
     */
636 19
    public function refresh($entity)
637
    {
638 19
        if ( ! is_object($entity)) {
639 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#refresh()', $entity);
640
        }
641
642 18
        $this->errorIfClosed();
643
644 17
        $this->unitOfWork->refresh($entity);
645 17
    }
646
647
    /**
648
     * Detaches an entity from the EntityManager, causing a managed entity to
649
     * become detached.  Unflushed changes made to the entity if any
650
     * (including removal of the entity), will not be synchronized to the database.
651
     * Entities which previously referenced the detached entity will continue to
652
     * reference it.
653
     *
654
     * @param object $entity The entity to detach.
655
     *
656
     * @return void
657
     *
658
     * @throws ORMInvalidArgumentException
659
     */
660 13
    public function detach($entity)
661
    {
662 13
        if ( ! is_object($entity)) {
663 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()', $entity);
664
        }
665
666 12
        $this->unitOfWork->detach($entity);
667 12
    }
668
669
    /**
670
     * Merges the state of a detached entity into the persistence context
671
     * of this EntityManager and returns the managed copy of the entity.
672
     * The entity passed to merge will not become associated/managed with this EntityManager.
673
     *
674
     * @param object $entity The detached entity to merge into the persistence context.
675
     *
676
     * @return object The managed copy of the entity.
677
     *
678
     * @throws ORMInvalidArgumentException
679
     * @throws ORMException
680
     */
681 42
    public function merge($entity)
682
    {
683 42
        if ( ! is_object($entity)) {
684 1
            throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()', $entity);
685
        }
686
687 41
        $this->errorIfClosed();
688
689 40
        return $this->unitOfWork->merge($entity);
690
    }
691
692
    /**
693
     * {@inheritDoc}
694
     */
695
    public function copy($entity, $deep = false)
696
    {
697
        throw new \BadMethodCallException("Not implemented.");
698
    }
699
700
    /**
701
     * {@inheritDoc}
702
     */
703 8
    public function lock($entity, $lockMode, $lockVersion = null)
704
    {
705 8
        $this->unitOfWork->lock($entity, $lockMode, $lockVersion);
706 2
    }
707
708
    /**
709
     * Gets the repository for an entity class.
710
     *
711
     * @param string $entityName The name of the entity.
712
     *
713
     * @return \Doctrine\Common\Persistence\ObjectRepository|\Doctrine\ORM\EntityRepository The repository class.
714
     */
715 160
    public function getRepository($entityName)
716
    {
717 160
        return $this->repositoryFactory->getRepository($this, $entityName);
718
    }
719
720
    /**
721
     * Determines whether an entity instance is managed in this EntityManager.
722
     *
723
     * @param object $entity
724
     *
725
     * @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise.
726
     */
727 24
    public function contains($entity)
728
    {
729 24
        return $this->unitOfWork->isScheduledForInsert($entity)
730 22
            || $this->unitOfWork->isInIdentityMap($entity)
731 24
            && ! $this->unitOfWork->isScheduledForDelete($entity);
732
    }
733
734
    /**
735
     * {@inheritDoc}
736
     */
737 2476
    public function getEventManager()
738
    {
739 2476
        return $this->eventManager;
740
    }
741
742
    /**
743
     * {@inheritDoc}
744
     */
745 2476
    public function getConfiguration()
746
    {
747 2476
        return $this->config;
748
    }
749
750
    /**
751
     * Throws an exception if the EntityManager is closed or currently not active.
752
     *
753
     * @return void
754
     *
755
     * @throws ORMException If the EntityManager is closed.
756
     */
757 1093
    private function errorIfClosed()
758
    {
759 1093
        if ($this->closed) {
760 5
            throw ORMException::entityManagerClosed();
761
        }
762 1088
    }
763
764
    /**
765
     * {@inheritDoc}
766
     */
767 2
    public function isOpen()
768
    {
769 2
        return (!$this->closed);
770
    }
771
772
    /**
773
     * {@inheritDoc}
774
     */
775 2476
    public function getUnitOfWork()
776
    {
777 2476
        return $this->unitOfWork;
778
    }
779
780
    /**
781
     * {@inheritDoc}
782
     */
783
    public function getHydrator($hydrationMode)
784
    {
785
        return $this->newHydrator($hydrationMode);
786
    }
787
788
    /**
789
     * {@inheritDoc}
790
     */
791 953
    public function newHydrator($hydrationMode)
792
    {
793
        switch ($hydrationMode) {
794 953
            case Query::HYDRATE_OBJECT:
795 653
                return new Internal\Hydration\ObjectHydrator($this);
796
797 585
            case Query::HYDRATE_ARRAY:
798 48
                return new Internal\Hydration\ArrayHydrator($this);
799
800 542
            case Query::HYDRATE_SCALAR:
801 85
                return new Internal\Hydration\ScalarHydrator($this);
802
803 459
            case Query::HYDRATE_SINGLE_SCALAR:
804 13
                return new Internal\Hydration\SingleScalarHydrator($this);
805
806 450
            case Query::HYDRATE_SIMPLEOBJECT:
807 449
                return new Internal\Hydration\SimpleObjectHydrator($this);
808
809
            default:
810 1
                if (($class = $this->config->getCustomHydrationMode($hydrationMode)) !== null) {
811 1
                    return new $class($this);
812
                }
813
        }
814
815
        throw ORMException::invalidHydrationMode($hydrationMode);
816
    }
817
818
    /**
819
     * {@inheritDoc}
820
     */
821 177
    public function getProxyFactory()
822
    {
823 177
        return $this->proxyFactory;
824
    }
825
826
    /**
827
     * {@inheritDoc}
828
     */
829
    public function initializeObject($obj)
830
    {
831
        $this->unitOfWork->initializeObject($obj);
832
    }
833
834
    /**
835
     * Factory method to create EntityManager instances.
836
     *
837
     * @param array|Connection $connection   An array with the connection parameters or an existing Connection instance.
838
     * @param Configuration    $config       The Configuration instance to use.
839
     * @param EventManager     $eventManager The EventManager instance to use.
840
     *
841
     * @return EntityManager The created EntityManager.
842
     *
843
     * @throws \InvalidArgumentException
844
     * @throws ORMException
845
     */
846 1307
    public static function create($connection, Configuration $config, EventManager $eventManager = null)
847
    {
848 1307
        if ( ! $config->getMetadataDriverImpl()) {
849
            throw ORMException::missingMappingDriverImpl();
850
        }
851
852 1307
        $connection = static::createConnection($connection, $config, $eventManager);
853
854 1306
        return new EntityManager($connection, $config, $connection->getEventManager());
855
    }
856
857
    /**
858
     * Factory method to create Connection instances.
859
     *
860
     * @param array|Connection $connection   An array with the connection parameters or an existing Connection instance.
861
     * @param Configuration    $config       The Configuration instance to use.
862
     * @param EventManager     $eventManager The EventManager instance to use.
863
     *
864
     * @return Connection
865
     *
866
     * @throws \InvalidArgumentException
867
     * @throws ORMException
868
     */
869 1307
    protected static function createConnection($connection, Configuration $config, EventManager $eventManager = null)
870
    {
871 1307
        if (is_array($connection)) {
872
            return DriverManager::getConnection($connection, $config, $eventManager ?: new EventManager());
873
        }
874
875 1307
        if ( ! $connection instanceof Connection) {
0 ignored issues
show
introduced by
$connection is always a sub-type of Doctrine\DBAL\Connection.
Loading history...
876 1
            throw new \InvalidArgumentException(
877 1
                sprintf(
878 1
                    'Invalid $connection argument of type %s given%s.',
879 1
                    is_object($connection) ? get_class($connection) : gettype($connection),
880 1
                    is_object($connection) ? '' : ': "' . $connection . '"'
881
                )
882
            );
883
        }
884
885 1306
        if ($eventManager !== null && $connection->getEventManager() !== $eventManager) {
886
            throw ORMException::mismatchedEventManager();
887
        }
888
889 1306
        return $connection;
890
    }
891
892
    /**
893
     * {@inheritDoc}
894
     */
895 642
    public function getFilters()
896
    {
897 642
        if (null === $this->filterCollection) {
898 642
            $this->filterCollection = new FilterCollection($this);
899
        }
900
901 642
        return $this->filterCollection;
902
    }
903
904
    /**
905
     * {@inheritDoc}
906
     */
907 40
    public function isFiltersStateClean()
908
    {
909 40
        return null === $this->filterCollection || $this->filterCollection->isClean();
910
    }
911
912
    /**
913
     * {@inheritDoc}
914
     */
915 782
    public function hasFilters()
916
    {
917 782
        return null !== $this->filterCollection;
918
    }
919
920
    /**
921
     * @param int $lockMode
922
     * @param ClassMetadata $class
923
     * @throws OptimisticLockException
924
     * @throws TransactionRequiredException
925
     */
926 6
    private function checkLockRequirements(int $lockMode, ClassMetadata $class): void
927
    {
928
        switch ($lockMode) {
929 6
            case LockMode::OPTIMISTIC:
930 3
                if (!$class->isVersioned) {
931 2
                    throw OptimisticLockException::notVersioned($class->name);
932
                }
933 1
                break;
934 3
            case LockMode::PESSIMISTIC_READ:
935 2
            case LockMode::PESSIMISTIC_WRITE:
936 3
                if (!$this->getConnection()->isTransactionActive()) {
937 3
                    throw TransactionRequiredException::transactionRequired();
938
                }
939
        }
940 1
    }
941
}
942