Completed
Push — 2.6 ( 46f2a4...1d71fb )
by Michael
83:49 queued 78:15
created

EntityManager::transactional()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 5
nop 1
dl 0
loc 20
rs 9.8666
c 0
b 0
f 0
ccs 12
cts 12
cp 1
crap 4
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 2473
    protected function __construct(Connection $conn, Configuration $config, EventManager $eventManager)
150
    {
151 2473
        $this->conn              = $conn;
152 2473
        $this->config            = $config;
153 2473
        $this->eventManager      = $eventManager;
154
155 2473
        $metadataFactoryClassName = $config->getClassMetadataFactoryName();
156
157 2473
        $this->metadataFactory = new $metadataFactoryClassName;
158 2473
        $this->metadataFactory->setEntityManager($this);
159 2473
        $this->metadataFactory->setCacheDriver($this->config->getMetadataCacheImpl());
160
161 2473
        $this->repositoryFactory = $config->getRepositoryFactory();
162 2473
        $this->unitOfWork        = new UnitOfWork($this);
163 2473
        $this->proxyFactory      = new ProxyFactory(
164 2473
            $this,
165 2473
            $config->getProxyDir(),
166 2473
            $config->getProxyNamespace(),
167 2473
            $config->getAutoGenerateProxyClasses()
168
        );
169
170 2473
        if ($config->isSecondLevelCacheEnabled()) {
171 286
            $cacheConfig    = $config->getSecondLevelCacheConfiguration();
172 286
            $cacheFactory   = $cacheConfig->getCacheFactory();
173 286
            $this->cache    = $cacheFactory->createCache($this);
174
        }
175 2473
    }
176
177
    /**
178
     * {@inheritDoc}
179
     */
180 1944
    public function getConnection()
181
    {
182 1944
        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 2473
    public function getMetadataFactory()
191
    {
192 2473
        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 3
            $this->conn->commit();
239
240 3
            return $return ?: true;
241 1
        } catch (Throwable $e) {
242 1
            $this->close();
243 1
            $this->conn->rollBack();
244
245 1
            throw $e;
246
        }
247
    }
248
249
    /**
250
     * {@inheritDoc}
251
     */
252 1
    public function commit()
253
    {
254 1
        $this->conn->commit();
255 1
    }
256
257
    /**
258
     * {@inheritDoc}
259
     */
260
    public function rollback()
261
    {
262
        $this->conn->rollBack();
263
    }
264
265
    /**
266
     * Returns the ORM metadata descriptor for a class.
267
     *
268
     * The class name must be the fully-qualified class name without a leading backslash
269
     * (as it is returned by get_class($obj)) or an aliased class name.
270
     *
271
     * Examples:
272
     * MyProject\Domain\User
273
     * sales:PriceRequest
274
     *
275
     * Internal note: Performance-sensitive method.
276
     *
277
     * @param string $className
278
     *
279
     * @return \Doctrine\ORM\Mapping\ClassMetadata
280
     */
281 2000
    public function getClassMetadata($className)
282
    {
283 2000
        return $this->metadataFactory->getMetadataFor($className);
284
    }
285
286
    /**
287
     * {@inheritDoc}
288
     */
289 976
    public function createQuery($dql = '')
290
    {
291 976
        $query = new Query($this);
292
293 976
        if ( ! empty($dql)) {
294 971
            $query->setDQL($dql);
295
        }
296
297 976
        return $query;
298
    }
299
300
    /**
301
     * {@inheritDoc}
302
     */
303 1
    public function createNamedQuery($name)
304
    {
305 1
        return $this->createQuery($this->config->getNamedQuery($name));
306
    }
307
308
    /**
309
     * {@inheritDoc}
310
     */
311 21
    public function createNativeQuery($sql, ResultSetMapping $rsm)
312
    {
313 21
        $query = new NativeQuery($this);
314
315 21
        $query->setSQL($sql);
316 21
        $query->setResultSetMapping($rsm);
317
318 21
        return $query;
319
    }
320
321
    /**
322
     * {@inheritDoc}
323
     */
324 1
    public function createNamedNativeQuery($name)
325
    {
326 1
        list($sql, $rsm) = $this->config->getNamedNativeQuery($name);
327
328 1
        return $this->createNativeQuery($sql, $rsm);
329
    }
330
331
    /**
332
     * {@inheritDoc}
333
     */
334 129
    public function createQueryBuilder()
335
    {
336 129
        return new QueryBuilder($this);
337
    }
338
339
    /**
340
     * Flushes all changes to objects that have been queued up to now to the database.
341
     * This effectively synchronizes the in-memory state of managed objects with the
342
     * database.
343
     *
344
     * If an entity is explicitly passed to this method only this entity and
345
     * the cascade-persist semantics + scheduled inserts/removals are synchronized.
346
     *
347
     * @param null|object|array $entity
348
     *
349
     * @return void
350
     *
351
     * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that
352
     *         makes use of optimistic locking fails.
353
     * @throws ORMException
354
     */
355 1078
    public function flush($entity = null)
356
    {
357 1078
        $this->errorIfClosed();
358
359 1077
        $this->unitOfWork->commit($entity);
360 1066
    }
361
362
    /**
363
     * Finds an Entity by its identifier.
364
     *
365
     * @param string       $entityName  The class name of the entity to find.
366
     * @param mixed        $id          The identity of the entity to find.
367
     * @param integer|null $lockMode    One of the \Doctrine\DBAL\LockMode::* constants
368
     *                                  or NULL if no specific lock mode should be used
369
     *                                  during the search.
370
     * @param integer|null $lockVersion The version of the entity to find when using
371
     *                                  optimistic locking.
372
     *
373
     * @return object|null The entity instance or NULL if the entity can not be found.
374
     *
375
     * @throws OptimisticLockException
376
     * @throws ORMInvalidArgumentException
377
     * @throws TransactionRequiredException
378
     * @throws ORMException
379
     */
380 443
    public function find($entityName, $id, $lockMode = null, $lockVersion = null)
381
    {
382 443
        $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
383
384 443
        if ($lockMode !== null) {
385 6
            $this->checkLockRequirements($lockMode, $class);
386
        }
387
388 440
        if ( ! is_array($id)) {
389 392
            if ($class->isIdentifierComposite) {
390
                throw ORMInvalidArgumentException::invalidCompositeIdentifier();
391
            }
392
393 392
            $id = [$class->identifier[0] => $id];
394
        }
395
396 440
        foreach ($id as $i => $value) {
397 440
            if (is_object($value) && $this->metadataFactory->hasMetadataFor(ClassUtils::getClass($value))) {
398 10
                $id[$i] = $this->unitOfWork->getSingleIdentifierValue($value);
399
400 10
                if ($id[$i] === null) {
401 440
                    throw ORMInvalidArgumentException::invalidIdentifierBindingEntity();
402
                }
403
            }
404
        }
405
406 439
        $sortedId = [];
407
408 439
        foreach ($class->identifier as $identifier) {
409 439
            if ( ! isset($id[$identifier])) {
410 1
                throw ORMException::missingIdentifierField($class->name, $identifier);
411
            }
412
413 438
            $sortedId[$identifier] = $id[$identifier];
414 438
            unset($id[$identifier]);
415
        }
416
417 438
        if ($id) {
418 1
            throw ORMException::unrecognizedIdentifierFields($class->name, array_keys($id));
419
        }
420
421 437
        $unitOfWork = $this->getUnitOfWork();
422
423
        // Check identity map first
424 437
        if (($entity = $unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) {
425 49
            if ( ! ($entity instanceof $class->name)) {
426 1
                return null;
427
            }
428
429
            switch (true) {
430 48
                case LockMode::OPTIMISTIC === $lockMode:
431
                    $this->lock($entity, $lockMode, $lockVersion);
432
                    break;
433
434 48
                case LockMode::NONE === $lockMode:
435 48
                case LockMode::PESSIMISTIC_READ === $lockMode:
436 48
                case LockMode::PESSIMISTIC_WRITE === $lockMode:
437
                    $persister = $unitOfWork->getEntityPersister($class->name);
438
                    $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

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