Failed Conditions
Push — master ( 7c9ab7...fa4d3b )
by Marco
13:03
created

lib/Doctrine/ORM/UnitOfWork.php (6 issues)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ORM;
6
7
use Doctrine\Common\Collections\Collection;
8
use Doctrine\Common\EventManager;
9
use Doctrine\Common\NotifyPropertyChanged;
10
use Doctrine\Common\PropertyChangedListener;
11
use Doctrine\DBAL\LockMode;
12
use Doctrine\Instantiator\Instantiator;
13
use Doctrine\ORM\Cache\Persister\CachedPersister;
14
use Doctrine\ORM\Event\LifecycleEventArgs;
15
use Doctrine\ORM\Event\ListenersInvoker;
16
use Doctrine\ORM\Event\OnFlushEventArgs;
17
use Doctrine\ORM\Event\PostFlushEventArgs;
18
use Doctrine\ORM\Event\PreFlushEventArgs;
19
use Doctrine\ORM\Event\PreUpdateEventArgs;
20
use Doctrine\ORM\Exception\UnexpectedAssociationValue;
21
use Doctrine\ORM\Internal\HydrationCompleteHandler;
22
use Doctrine\ORM\Mapping\AssociationMetadata;
23
use Doctrine\ORM\Mapping\ChangeTrackingPolicy;
24
use Doctrine\ORM\Mapping\ClassMetadata;
25
use Doctrine\ORM\Mapping\FetchMode;
26
use Doctrine\ORM\Mapping\FieldMetadata;
27
use Doctrine\ORM\Mapping\GeneratorType;
28
use Doctrine\ORM\Mapping\InheritanceType;
29
use Doctrine\ORM\Mapping\JoinColumnMetadata;
30
use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata;
31
use Doctrine\ORM\Mapping\OneToManyAssociationMetadata;
32
use Doctrine\ORM\Mapping\OneToOneAssociationMetadata;
33
use Doctrine\ORM\Mapping\ToManyAssociationMetadata;
34
use Doctrine\ORM\Mapping\ToOneAssociationMetadata;
35
use Doctrine\ORM\Mapping\VersionFieldMetadata;
36
use Doctrine\ORM\Persisters\Collection\CollectionPersister;
37
use Doctrine\ORM\Persisters\Collection\ManyToManyPersister;
38
use Doctrine\ORM\Persisters\Collection\OneToManyPersister;
39
use Doctrine\ORM\Persisters\Entity\BasicEntityPersister;
40
use Doctrine\ORM\Persisters\Entity\EntityPersister;
41
use Doctrine\ORM\Persisters\Entity\JoinedSubclassPersister;
42
use Doctrine\ORM\Persisters\Entity\SingleTablePersister;
43
use Doctrine\ORM\Utility\NormalizeIdentifier;
44
use Exception;
45
use InvalidArgumentException;
46
use ProxyManager\Proxy\GhostObjectInterface;
47
use RuntimeException;
48
use Throwable;
49
use UnexpectedValueException;
50
use function array_combine;
51
use function array_diff_key;
52
use function array_filter;
53
use function array_key_exists;
54
use function array_map;
55
use function array_merge;
56
use function array_pop;
57
use function array_reverse;
58
use function array_sum;
59
use function array_values;
60
use function current;
61
use function get_class;
62
use function implode;
63
use function in_array;
64
use function is_array;
65
use function is_object;
66
use function method_exists;
67
use function spl_object_id;
68
use function sprintf;
69
70
/**
71
 * The UnitOfWork is responsible for tracking changes to objects during an
72
 * "object-level" transaction and for writing out changes to the database
73
 * in the correct order.
74
 *
75
 * {@internal This class contains highly performance-sensitive code. }}
76
 */
77
class UnitOfWork implements PropertyChangedListener
78
{
79
    /**
80
     * An entity is in MANAGED state when its persistence is managed by an EntityManager.
81
     */
82
    public const STATE_MANAGED = 1;
83
84
    /**
85
     * An entity is new if it has just been instantiated (i.e. using the "new" operator)
86
     * and is not (yet) managed by an EntityManager.
87
     */
88
    public const STATE_NEW = 2;
89
90
    /**
91
     * A detached entity is an instance with persistent state and identity that is not
92
     * (or no longer) associated with an EntityManager (and a UnitOfWork).
93
     */
94
    public const STATE_DETACHED = 3;
95
96
    /**
97
     * A removed entity instance is an instance with a persistent identity,
98
     * associated with an EntityManager, whose persistent state will be deleted
99
     * on commit.
100
     */
101
    public const STATE_REMOVED = 4;
102
103
    /**
104
     * Hint used to collect all primary keys of associated entities during hydration
105
     * and execute it in a dedicated query afterwards
106
     *
107
     * @see https://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html?highlight=eager#temporarily-change-fetch-mode-in-dql
108
     */
109
    public const HINT_DEFEREAGERLOAD = 'deferEagerLoad';
110
111
    /**
112
     * The identity map that holds references to all managed entities that have
113
     * an identity. The entities are grouped by their class name.
114
     * Since all classes in a hierarchy must share the same identifier set,
115
     * we always take the root class name of the hierarchy.
116
     *
117
     * @var object[]
118
     */
119
    private $identityMap = [];
120
121
    /**
122
     * Map of all identifiers of managed entities.
123
     * This is a 2-dimensional data structure (map of maps). Keys are object ids (spl_object_id).
124
     * Values are maps of entity identifiers, where its key is the column name and the value is the raw value.
125
     *
126
     * @var mixed[][]
127
     */
128
    private $entityIdentifiers = [];
129
130
    /**
131
     * Map of the original entity data of managed entities.
132
     * This is a 2-dimensional data structure (map of maps). Keys are object ids (spl_object_id).
133
     * Values are maps of entity data, where its key is the field name and the value is the converted
134
     * (convertToPHPValue) value.
135
     * This structure is used for calculating changesets at commit time.
136
     *
137
     * Internal: Note that PHPs "copy-on-write" behavior helps a lot with memory usage.
138
     *           A value will only really be copied if the value in the entity is modified by the user.
139
     *
140
     * @var mixed[][]
141
     */
142
    private $originalEntityData = [];
143
144
    /**
145
     * Map of entity changes. Keys are object ids (spl_object_id).
146
     * Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
147
     *
148
     * @var mixed[][]
149
     */
150
    private $entityChangeSets = [];
151
152
    /**
153
     * The (cached) states of any known entities.
154
     * Keys are object ids (spl_object_id).
155
     *
156
     * @var int[]
157
     */
158
    private $entityStates = [];
159
160
    /**
161
     * Map of entities that are scheduled for dirty checking at commit time.
162
     * This is only used for entities with a change tracking policy of DEFERRED_EXPLICIT.
163
     * Keys are object ids (spl_object_id).
164
     *
165
     * @var object[][]
166
     */
167
    private $scheduledForSynchronization = [];
168
169
    /**
170
     * A list of all pending entity insertions.
171
     *
172
     * @var object[]
173
     */
174
    private $entityInsertions = [];
175
176
    /**
177
     * A list of all pending entity updates.
178
     *
179
     * @var object[]
180
     */
181
    private $entityUpdates = [];
182
183
    /**
184
     * Any pending extra updates that have been scheduled by persisters.
185
     *
186
     * @var object[]
187
     */
188
    private $extraUpdates = [];
189
190
    /**
191
     * A list of all pending entity deletions.
192
     *
193
     * @var object[]
194
     */
195
    private $entityDeletions = [];
196
197
    /**
198
     * New entities that were discovered through relationships that were not
199
     * marked as cascade-persist. During flush, this array is populated and
200
     * then pruned of any entities that were discovered through a valid
201
     * cascade-persist path. (Leftovers cause an error.)
202
     *
203
     * Keys are OIDs, payload is a two-item array describing the association
204
     * and the entity.
205
     *
206
     * @var object[][]|array[][] indexed by respective object spl_object_id()
207
     */
208
    private $nonCascadedNewDetectedEntities = [];
209
210
    /**
211
     * All pending collection deletions.
212
     *
213
     * @var Collection[]|object[][]
214
     */
215
    private $collectionDeletions = [];
216
217
    /**
218
     * All pending collection updates.
219
     *
220
     * @var Collection[]|object[][]
221
     */
222
    private $collectionUpdates = [];
223
224
    /**
225
     * List of collections visited during changeset calculation on a commit-phase of a UnitOfWork.
226
     * At the end of the UnitOfWork all these collections will make new snapshots
227
     * of their data.
228
     *
229
     * @var Collection[]|object[][]
230
     */
231
    private $visitedCollections = [];
232
233
    /**
234
     * The EntityManager that "owns" this UnitOfWork instance.
235
     *
236
     * @var EntityManagerInterface
237
     */
238
    private $em;
239
240
    /**
241
     * The entity persister instances used to persist entity instances.
242
     *
243
     * @var EntityPersister[]
244
     */
245
    private $entityPersisters = [];
246
247
    /**
248
     * The collection persister instances used to persist collections.
249
     *
250
     * @var CollectionPersister[]
251
     */
252
    private $collectionPersisters = [];
253
254
    /**
255
     * The EventManager used for dispatching events.
256
     *
257
     * @var EventManager
258
     */
259
    private $eventManager;
260
261
    /**
262
     * The ListenersInvoker used for dispatching events.
263
     *
264
     * @var ListenersInvoker
265
     */
266
    private $listenersInvoker;
267
268
    /** @var Instantiator */
269
    private $instantiator;
270
271
    /**
272
     * Orphaned entities that are scheduled for removal.
273
     *
274
     * @var object[]
275
     */
276
    private $orphanRemovals = [];
277
278
    /**
279
     * Read-Only objects are never evaluated
280
     *
281
     * @var object[]
282
     */
283
    private $readOnlyObjects = [];
284
285
    /**
286
     * Map of Entity Class-Names and corresponding IDs that should eager loaded when requested.
287
     *
288
     * @var mixed[][][]
289
     */
290
    private $eagerLoadingEntities = [];
291
292
    /** @var bool */
293
    protected $hasCache = false;
294
295
    /**
296
     * Helper for handling completion of hydration
297
     *
298
     * @var HydrationCompleteHandler
299
     */
300
    private $hydrationCompleteHandler;
301
302
    /** @var NormalizeIdentifier */
303
    private $normalizeIdentifier;
304
305
    /**
306
     * Initializes a new UnitOfWork instance, bound to the given EntityManager.
307
     */
308 2263
    public function __construct(EntityManagerInterface $em)
309
    {
310 2263
        $this->em                       = $em;
311 2263
        $this->eventManager             = $em->getEventManager();
312 2263
        $this->listenersInvoker         = new ListenersInvoker($em);
313 2263
        $this->hasCache                 = $em->getConfiguration()->isSecondLevelCacheEnabled();
314 2263
        $this->instantiator             = new Instantiator();
315 2263
        $this->hydrationCompleteHandler = new HydrationCompleteHandler($this->listenersInvoker, $em);
316 2263
        $this->normalizeIdentifier      = new NormalizeIdentifier();
317 2263
    }
318
319
    /**
320
     * Commits the UnitOfWork, executing all operations that have been postponed
321
     * up to this point. The state of all managed entities will be synchronized with
322
     * the database.
323
     *
324
     * The operations are executed in the following order:
325
     *
326
     * 1) All entity insertions
327
     * 2) All entity updates
328
     * 3) All collection deletions
329
     * 4) All collection updates
330
     * 5) All entity deletions
331
     *
332
     * @throws Exception
333
     */
334 1018
    public function commit()
335
    {
336
        // Raise preFlush
337 1018
        if ($this->eventManager->hasListeners(Events::preFlush)) {
338 2
            $this->eventManager->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em));
339
        }
340
341 1018
        $this->computeChangeSets();
342
343 1016
        if (! ($this->entityInsertions ||
344 157
                $this->entityDeletions ||
345 122
                $this->entityUpdates ||
346 36
                $this->collectionUpdates ||
347 33
                $this->collectionDeletions ||
348 1016
                $this->orphanRemovals)) {
349 21
            $this->dispatchOnFlushEvent();
350 21
            $this->dispatchPostFlushEvent();
351
352 21
            return; // Nothing to do.
353
        }
354
355 1011
        $this->assertThatThereAreNoUnintentionallyNonPersistedAssociations();
356
357 1009
        if ($this->orphanRemovals) {
358 15
            foreach ($this->orphanRemovals as $orphan) {
359 15
                $this->remove($orphan);
360
            }
361
        }
362
363 1009
        $this->dispatchOnFlushEvent();
364
365
        // Now we need a commit order to maintain referential integrity
366 1009
        $commitOrder = $this->getCommitOrder();
367
368 1009
        $conn = $this->em->getConnection();
369 1009
        $conn->beginTransaction();
370
371
        try {
372
            // Collection deletions (deletions of complete collections)
373 1009
            foreach ($this->collectionDeletions as $collectionToDelete) {
374 19
                $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
375
            }
376
377 1009
            if ($this->entityInsertions) {
378 1005
                foreach ($commitOrder as $class) {
379 1005
                    $this->executeInserts($class);
380
                }
381
            }
382
383 1008
            if ($this->entityUpdates) {
384 111
                foreach ($commitOrder as $class) {
385 111
                    $this->executeUpdates($class);
386
                }
387
            }
388
389
            // Extra updates that were requested by persisters.
390 1004
            if ($this->extraUpdates) {
391 29
                $this->executeExtraUpdates();
392
            }
393
394
            // Collection updates (deleteRows, updateRows, insertRows)
395 1004
            foreach ($this->collectionUpdates as $collectionToUpdate) {
396 526
                $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
397
            }
398
399
            // Entity deletions come last and need to be in reverse commit order
400 1004
            if ($this->entityDeletions) {
401 60
                foreach (array_reverse($commitOrder) as $committedEntityName) {
402 60
                    if (! $this->entityDeletions) {
403 33
                        break; // just a performance optimisation
404
                    }
405
406 60
                    $this->executeDeletions($committedEntityName);
407
                }
408
            }
409
410 1004
            $conn->commit();
411 10
        } catch (Throwable $e) {
412 10
            $this->em->close();
413 10
            $conn->rollBack();
414
415 10
            $this->afterTransactionRolledBack();
416
417 10
            throw $e;
418
        }
419
420 1004
        $this->afterTransactionComplete();
421
422
        // Take new snapshots from visited collections
423 1004
        foreach ($this->visitedCollections as $coll) {
424 525
            $coll->takeSnapshot();
425
        }
426
427 1004
        $this->dispatchPostFlushEvent();
428
429
        // Clean up
430 1003
        $this->entityInsertions            =
431 1003
        $this->entityUpdates               =
432 1003
        $this->entityDeletions             =
433 1003
        $this->extraUpdates                =
434 1003
        $this->entityChangeSets            =
435 1003
        $this->collectionUpdates           =
436 1003
        $this->collectionDeletions         =
437 1003
        $this->visitedCollections          =
438 1003
        $this->scheduledForSynchronization =
439 1003
        $this->orphanRemovals              = [];
440 1003
    }
441
442
    /**
443
     * Computes the changesets of all entities scheduled for insertion.
444
     */
445 1018
    private function computeScheduleInsertsChangeSets()
446
    {
447 1018
        foreach ($this->entityInsertions as $entity) {
448 1009
            $class = $this->em->getClassMetadata(get_class($entity));
449
450 1009
            $this->computeChangeSet($class, $entity);
451
        }
452 1016
    }
453
454
    /**
455
     * Executes any extra updates that have been scheduled.
456
     */
457 29
    private function executeExtraUpdates()
458
    {
459 29
        foreach ($this->extraUpdates as $oid => $update) {
460 29
            [$entity, $changeset] = $update;
461
462 29
            $this->entityChangeSets[$oid] = $changeset;
463
464 29
            $this->getEntityPersister(get_class($entity))->update($entity);
465
        }
466
467 29
        $this->extraUpdates = [];
468 29
    }
469
470
    /**
471
     * Gets the changeset for an entity.
472
     *
473
     * @param object $entity
474
     *
475
     * @return mixed[]
476
     */
477
    public function & getEntityChangeSet($entity)
478
    {
479 1004
        $oid  = spl_object_id($entity);
480 1004
        $data = [];
481
482 1004
        if (! isset($this->entityChangeSets[$oid])) {
483 2
            return $data;
484
        }
485
486 1004
        return $this->entityChangeSets[$oid];
487
    }
488
489
    /**
490
     * Computes the changes that happened to a single entity.
491
     *
492
     * Modifies/populates the following properties:
493
     *
494
     * {@link originalEntityData}
495
     * If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
496
     * then it was not fetched from the database and therefore we have no original
497
     * entity data yet. All of the current entity data is stored as the original entity data.
498
     *
499
     * {@link entityChangeSets}
500
     * The changes detected on all properties of the entity are stored there.
501
     * A change is a tuple array where the first entry is the old value and the second
502
     * entry is the new value of the property. Changesets are used by persisters
503
     * to INSERT/UPDATE the persistent entity state.
504
     *
505
     * {@link entityUpdates}
506
     * If the entity is already fully MANAGED (has been fetched from the database before)
507
     * and any changes to its properties are detected, then a reference to the entity is stored
508
     * there to mark it for an update.
509
     *
510
     * {@link collectionDeletions}
511
     * If a PersistentCollection has been de-referenced in a fully MANAGED entity,
512
     * then this collection is marked for deletion.
513
     *
514
     * @internal Don't call from the outside.
515
     *
516
     * @param ClassMetadata $class  The class descriptor of the entity.
517
     * @param object        $entity The entity for which to compute the changes.
518
     *
519
     * @ignore
520
     */
521 1019
    public function computeChangeSet(ClassMetadata $class, $entity)
522
    {
523 1019
        $oid = spl_object_id($entity);
524
525 1019
        if (isset($this->readOnlyObjects[$oid])) {
526 2
            return;
527
        }
528
529 1019
        if ($class->inheritanceType !== InheritanceType::NONE) {
530 333
            $class = $this->em->getClassMetadata(get_class($entity));
531
        }
532
533 1019
        $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preFlush) & ~ListenersInvoker::INVOKE_MANAGER;
534
535 1019
        if ($invoke !== ListenersInvoker::INVOKE_NONE) {
536 130
            $this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke);
0 ignored issues
show
It seems like $class can also be of type Doctrine\Common\Persistence\Mapping\ClassMetadata; however, parameter $metadata of Doctrine\ORM\Event\ListenersInvoker::invoke() does only seem to accept Doctrine\ORM\Mapping\ClassMetadata, 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

536
            $this->listenersInvoker->invoke(/** @scrutinizer ignore-type */ $class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke);
Loading history...
537
        }
538
539 1019
        $actualData = [];
540
541 1019
        foreach ($class->getDeclaredPropertiesIterator() as $name => $property) {
542 1019
            $value = $property->getValue($entity);
543
544 1019
            if ($property instanceof ToManyAssociationMetadata && $value !== null) {
545 773
                if ($value instanceof PersistentCollection && $value->getOwner() === $entity) {
546 186
                    continue;
547
                }
548
549 770
                $value = $property->wrap($entity, $value, $this->em);
550
551 770
                $property->setValue($entity, $value);
552
553 770
                $actualData[$name] = $value;
554
555 770
                continue;
556
            }
557
558 1019
            if (( ! $class->isIdentifier($name)
559 1019
                    || ! $class->getProperty($name) instanceof FieldMetadata
560 1019
                    || ! $class->getProperty($name)->hasValueGenerator()
561 1019
                    || $class->getProperty($name)->getValueGenerator()->getType() !== GeneratorType::IDENTITY
562 1019
                ) && (! $class->isVersioned() || $name !== $class->versionProperty->getName())) {
563 1019
                $actualData[$name] = $value;
564
            }
565
        }
566
567 1019
        if (! isset($this->originalEntityData[$oid])) {
568
            // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
569
            // These result in an INSERT.
570 1015
            $this->originalEntityData[$oid] = $actualData;
571 1015
            $changeSet                      = [];
572
573 1015
            foreach ($actualData as $propName => $actualValue) {
574 994
                $property = $class->getProperty($propName);
575
576 994
                if (($property instanceof FieldMetadata) ||
577 994
                    ($property instanceof ToOneAssociationMetadata && $property->isOwningSide())) {
578 994
                    $changeSet[$propName] = [null, $actualValue];
579
                }
580
            }
581
582 1015
            $this->entityChangeSets[$oid] = $changeSet;
583
        } else {
584
            // Entity is "fully" MANAGED: it was already fully persisted before
585
            // and we have a copy of the original data
586 256
            $originalData           = $this->originalEntityData[$oid];
587 256
            $isChangeTrackingNotify = $class->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY;
588 256
            $changeSet              = $isChangeTrackingNotify && isset($this->entityChangeSets[$oid])
589
                ? $this->entityChangeSets[$oid]
590 256
                : [];
591
592 256
            foreach ($actualData as $propName => $actualValue) {
593
                // skip field, its a partially omitted one!
594 245
                if (! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
595 40
                    continue;
596
                }
597
598 245
                $orgValue = $originalData[$propName];
599
600
                // skip if value haven't changed
601 245
                if ($orgValue === $actualValue) {
602 228
                    continue;
603
                }
604
605 109
                $property = $class->getProperty($propName);
606
607
                // Persistent collection was exchanged with the "originally"
608
                // created one. This can only mean it was cloned and replaced
609
                // on another entity.
610 109
                if ($actualValue instanceof PersistentCollection) {
611 8
                    $owner = $actualValue->getOwner();
612
613 8
                    if ($owner === null) { // cloned
614
                        $actualValue->setOwner($entity, $property);
615 8
                    } elseif ($owner !== $entity) { // no clone, we have to fix
616
                        if (! $actualValue->isInitialized()) {
617
                            $actualValue->initialize(); // we have to do this otherwise the cols share state
618
                        }
619
620
                        $newValue = clone $actualValue;
621
622
                        $newValue->setOwner($entity, $property);
623
624
                        $property->setValue($entity, $newValue);
625
                    }
626
                }
627
628
                switch (true) {
629 109
                    case $property instanceof FieldMetadata:
630 58
                        if ($isChangeTrackingNotify) {
631
                            // Continue inside switch behaves as break.
632
                            // We are required to use continue 2, since we need to continue to next $actualData item
633
                            continue 2;
634
                        }
635
636 58
                        $changeSet[$propName] = [$orgValue, $actualValue];
637 58
                        break;
638
639 57
                    case $property instanceof ToOneAssociationMetadata:
640 46
                        if ($property->isOwningSide()) {
641 20
                            $changeSet[$propName] = [$orgValue, $actualValue];
642
                        }
643
644 46
                        if ($orgValue !== null && $property->isOrphanRemoval()) {
645 4
                            $this->scheduleOrphanRemoval($orgValue);
646
                        }
647
648 46
                        break;
649
650 12
                    case $property instanceof ToManyAssociationMetadata:
651
                        // Check if original value exists
652 9
                        if ($orgValue instanceof PersistentCollection) {
653
                            // A PersistentCollection was de-referenced, so delete it.
654 8
                            if (! $this->isCollectionScheduledForDeletion($orgValue)) {
655 8
                                $this->scheduleCollectionDeletion($orgValue);
656
657 8
                                $changeSet[$propName] = $orgValue; // Signal changeset, to-many associations will be ignored
658
                            }
659
                        }
660
661 9
                        break;
662
663 109
                    default:
664
                        // Do nothing
665
                }
666
            }
667
668 256
            if ($changeSet) {
669 84
                $this->entityChangeSets[$oid]   = $changeSet;
670 84
                $this->originalEntityData[$oid] = $actualData;
671 84
                $this->entityUpdates[$oid]      = $entity;
672
            }
673
        }
674
675
        // Look for changes in associations of the entity
676 1019
        foreach ($class->getDeclaredPropertiesIterator() as $property) {
677 1019
            if (! $property instanceof AssociationMetadata) {
678 1019
                continue;
679
            }
680
681 886
            $value = $property->getValue($entity);
682
683 886
            if ($value === null) {
684 625
                continue;
685
            }
686
687 862
            $this->computeAssociationChanges($property, $value);
688
689 854
            if ($property instanceof ManyToManyAssociationMetadata &&
690 854
                $value instanceof PersistentCollection &&
691 854
                ! isset($this->entityChangeSets[$oid]) &&
692 854
                $property->isOwningSide() &&
693 854
                $value->isDirty()) {
694 31
                $this->entityChangeSets[$oid]   = [];
695 31
                $this->originalEntityData[$oid] = $actualData;
696 854
                $this->entityUpdates[$oid]      = $entity;
697
            }
698
        }
699 1011
    }
700
701
    /**
702
     * Computes all the changes that have been done to entities and collections
703
     * since the last commit and stores these changes in the _entityChangeSet map
704
     * temporarily for access by the persisters, until the UoW commit is finished.
705
     */
706 1018
    public function computeChangeSets()
707
    {
708
        // Compute changes for INSERTed entities first. This must always happen.
709 1018
        $this->computeScheduleInsertsChangeSets();
710
711
        // Compute changes for other MANAGED entities. Change tracking policies take effect here.
712 1016
        foreach ($this->identityMap as $className => $entities) {
713 445
            $class = $this->em->getClassMetadata($className);
714
715
            // Skip class if instances are read-only
716 445
            if ($class->isReadOnly()) {
717 1
                continue;
718
            }
719
720
            // If change tracking is explicit or happens through notification, then only compute
721
            // changes on entities of that type that are explicitly marked for synchronization.
722
            switch (true) {
723 444
                case $class->changeTrackingPolicy === ChangeTrackingPolicy::DEFERRED_IMPLICIT:
724 442
                    $entitiesToProcess = $entities;
725 442
                    break;
726
727 3
                case isset($this->scheduledForSynchronization[$className]):
728 3
                    $entitiesToProcess = $this->scheduledForSynchronization[$className];
729 3
                    break;
730
731
                default:
732 1
                    $entitiesToProcess = [];
733
            }
734
735 444
            foreach ($entitiesToProcess as $entity) {
736
                // Ignore uninitialized proxy objects
737 424
                if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
738 38
                    continue;
739
                }
740
741
                // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
742 422
                $oid = spl_object_id($entity);
743
744 422
                if (! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
745 444
                    $this->computeChangeSet($class, $entity);
746
                }
747
            }
748
        }
749 1016
    }
750
751
    /**
752
     * Computes the changes of an association.
753
     *
754
     * @param AssociationMetadata $association The association mapping.
755
     * @param mixed               $value       The value of the association.
756
     *
757
     * @throws ORMInvalidArgumentException
758
     * @throws ORMException
759
     */
760 862
    private function computeAssociationChanges(AssociationMetadata $association, $value)
761
    {
762 862
        if ($value instanceof GhostObjectInterface && ! $value->isProxyInitialized()) {
763 31
            return;
764
        }
765
766 861
        if ($value instanceof PersistentCollection && $value->isDirty()) {
767 529
            $coid = spl_object_id($value);
768
769 529
            $this->collectionUpdates[$coid]  = $value;
770 529
            $this->visitedCollections[$coid] = $value;
771
        }
772
773
        // Look through the entities, and in any of their associations,
774
        // for transient (new) entities, recursively. ("Persistence by reachability")
775
        // Unwrap. Uninitialized collections will simply be empty.
776 861
        $unwrappedValue = $association instanceof ToOneAssociationMetadata ? [$value] : $value->unwrap();
777 861
        $targetEntity   = $association->getTargetEntity();
778 861
        $targetClass    = $this->em->getClassMetadata($targetEntity);
779
780 861
        foreach ($unwrappedValue as $key => $entry) {
781 718
            if (! ($entry instanceof $targetEntity)) {
782 8
                throw ORMInvalidArgumentException::invalidAssociation($targetClass, $association, $entry);
783
            }
784
785 710
            $state = $this->getEntityState($entry, self::STATE_NEW);
786
787 710
            if (! ($entry instanceof $targetEntity)) {
788
                throw UnexpectedAssociationValue::create(
789
                    $association->getSourceEntity(),
790
                    $association->getName(),
791
                    get_class($entry),
792
                    $targetEntity
793
                );
794
            }
795
796
            switch ($state) {
797 710
                case self::STATE_NEW:
798 41
                    if (! in_array('persist', $association->getCascade(), true)) {
799 5
                        $this->nonCascadedNewDetectedEntities[spl_object_id($entry)] = [$association, $entry];
800
801 5
                        break;
802
                    }
803
804 37
                    $this->persistNew($targetClass, $entry);
0 ignored issues
show
$targetClass of type Doctrine\Common\Persistence\Mapping\ClassMetadata is incompatible with the type Doctrine\ORM\Mapping\ClassMetadata expected by parameter $class of Doctrine\ORM\UnitOfWork::persistNew(). ( Ignorable by Annotation )

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

804
                    $this->persistNew(/** @scrutinizer ignore-type */ $targetClass, $entry);
Loading history...
805 37
                    $this->computeChangeSet($targetClass, $entry);
0 ignored issues
show
$targetClass of type Doctrine\Common\Persistence\Mapping\ClassMetadata is incompatible with the type Doctrine\ORM\Mapping\ClassMetadata expected by parameter $class of Doctrine\ORM\UnitOfWork::computeChangeSet(). ( Ignorable by Annotation )

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

805
                    $this->computeChangeSet(/** @scrutinizer ignore-type */ $targetClass, $entry);
Loading history...
806
807 37
                    break;
808
809 703
                case self::STATE_REMOVED:
810
                    // Consume the $value as array (it's either an array or an ArrayAccess)
811
                    // and remove the element from Collection.
812 4
                    if ($association instanceof ToManyAssociationMetadata) {
813 3
                        unset($value[$key]);
814
                    }
815 4
                    break;
816
817 703
                case self::STATE_DETACHED:
818
                    // Can actually not happen right now as we assume STATE_NEW,
819
                    // so the exception will be raised from the DBAL layer (constraint violation).
820
                    throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($association, $entry);
821
                    break;
822
823 710
                default:
824
                    // MANAGED associated entities are already taken into account
825
                    // during changeset calculation anyway, since they are in the identity map.
826
            }
827
        }
828 853
    }
829
830
    /**
831
     * @param ClassMetadata $class
832
     * @param object        $entity
833
     */
834 1030
    private function persistNew($class, $entity)
835
    {
836 1030
        $oid    = spl_object_id($entity);
837 1030
        $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::prePersist);
838
839 1030
        if ($invoke !== ListenersInvoker::INVOKE_NONE) {
840 132
            $this->listenersInvoker->invoke($class, Events::prePersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
841
        }
842
843 1030
        $generationPlan = $class->getValueGenerationPlan();
844 1030
        $persister      = $this->getEntityPersister($class->getClassName());
845 1030
        $generationPlan->executeImmediate($this->em, $entity);
846
847 1030
        if (! $generationPlan->containsDeferred()) {
848 221
            $id                            = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $persister->getIdentifier($entity));
849 221
            $this->entityIdentifiers[$oid] = $id;
850
        }
851
852 1030
        $this->entityStates[$oid] = self::STATE_MANAGED;
853
854 1030
        $this->scheduleForInsert($entity);
855 1030
    }
856
857
    /**
858
     * INTERNAL:
859
     * Computes the changeset of an individual entity, independently of the
860
     * computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
861
     *
862
     * The passed entity must be a managed entity. If the entity already has a change set
863
     * because this method is invoked during a commit cycle then the change sets are added.
864
     * whereby changes detected in this method prevail.
865
     *
866
     * @param ClassMetadata $class  The class descriptor of the entity.
867
     * @param object        $entity The entity for which to (re)calculate the change set.
868
     *
869
     * @throws ORMInvalidArgumentException If the passed entity is not MANAGED.
870
     * @throws RuntimeException
871
     *
872
     * @ignore
873
     */
874 15
    public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) : void
875
    {
876 15
        $oid = spl_object_id($entity);
877
878 15
        if (! isset($this->entityStates[$oid]) || $this->entityStates[$oid] !== self::STATE_MANAGED) {
879
            throw ORMInvalidArgumentException::entityNotManaged($entity);
880
        }
881
882
        // skip if change tracking is "NOTIFY"
883 15
        if ($class->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY) {
884
            return;
885
        }
886
887 15
        if ($class->inheritanceType !== InheritanceType::NONE) {
888 3
            $class = $this->em->getClassMetadata(get_class($entity));
889
        }
890
891 15
        $actualData = [];
892
893 15
        foreach ($class->getDeclaredPropertiesIterator() as $name => $property) {
894
            switch (true) {
895 15
                case $property instanceof VersionFieldMetadata:
896
                    // Ignore version field
897
                    break;
898
899 15
                case $property instanceof FieldMetadata:
900 15
                    if (! $property->isPrimaryKey()
901 15
                        || ! $property->getValueGenerator()
902 15
                        || $property->getValueGenerator()->getType() !== GeneratorType::IDENTITY) {
903 15
                        $actualData[$name] = $property->getValue($entity);
904
                    }
905
906 15
                    break;
907
908 11
                case $property instanceof ToOneAssociationMetadata:
909 9
                    $actualData[$name] = $property->getValue($entity);
910 15
                    break;
911
            }
912
        }
913
914 15
        if (! isset($this->originalEntityData[$oid])) {
915
            throw new RuntimeException('Cannot call recomputeSingleEntityChangeSet before computeChangeSet on an entity.');
916
        }
917
918 15
        $originalData = $this->originalEntityData[$oid];
919 15
        $changeSet    = [];
920
921 15
        foreach ($actualData as $propName => $actualValue) {
922 15
            $orgValue = $originalData[$propName] ?? null;
923
924 15
            if ($orgValue !== $actualValue) {
925 15
                $changeSet[$propName] = [$orgValue, $actualValue];
926
            }
927
        }
928
929 15
        if ($changeSet) {
930 7
            if (isset($this->entityChangeSets[$oid])) {
931 6
                $this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
932 1
            } elseif (! isset($this->entityInsertions[$oid])) {
933 1
                $this->entityChangeSets[$oid] = $changeSet;
934 1
                $this->entityUpdates[$oid]    = $entity;
935
            }
936 7
            $this->originalEntityData[$oid] = $actualData;
937
        }
938 15
    }
939
940
    /**
941
     * Executes all entity insertions for entities of the specified type.
942
     */
943 1005
    private function executeInserts(ClassMetadata $class) : void
944
    {
945 1005
        $className      = $class->getClassName();
946 1005
        $persister      = $this->getEntityPersister($className);
947 1005
        $invoke         = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist);
948 1005
        $generationPlan = $class->getValueGenerationPlan();
949
950 1005
        foreach ($this->entityInsertions as $oid => $entity) {
951 1005
            if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) {
952 854
                continue;
953
            }
954
955 1005
            $persister->insert($entity);
956
957 1004
            if ($generationPlan->containsDeferred()) {
958
                // Entity has post-insert IDs
959 941
                $oid = spl_object_id($entity);
960 941
                $id  = $persister->getIdentifier($entity);
961
962 941
                $this->entityIdentifiers[$oid]  = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $id);
963 941
                $this->entityStates[$oid]       = self::STATE_MANAGED;
964 941
                $this->originalEntityData[$oid] = $id + $this->originalEntityData[$oid];
965
966 941
                $this->addToIdentityMap($entity);
967
            }
968
969 1004
            unset($this->entityInsertions[$oid]);
970
971 1004
            if ($invoke !== ListenersInvoker::INVOKE_NONE) {
972 128
                $eventArgs = new LifecycleEventArgs($entity, $this->em);
973
974 1004
                $this->listenersInvoker->invoke($class, Events::postPersist, $entity, $eventArgs, $invoke);
975
            }
976
        }
977 1005
    }
978
979
    /**
980
     * Executes all entity updates for entities of the specified type.
981
     *
982
     * @param ClassMetadata $class
983
     */
984 111
    private function executeUpdates($class)
985
    {
986 111
        $className        = $class->getClassName();
987 111
        $persister        = $this->getEntityPersister($className);
988 111
        $preUpdateInvoke  = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate);
989 111
        $postUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate);
990
991 111
        foreach ($this->entityUpdates as $oid => $entity) {
992 111
            if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) {
993 71
                continue;
994
            }
995
996 111
            if ($preUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
997 12
                $this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->getEntityChangeSet($entity)), $preUpdateInvoke);
998
999 12
                $this->recomputeSingleEntityChangeSet($class, $entity);
1000
            }
1001
1002 111
            if (! empty($this->entityChangeSets[$oid])) {
1003 81
                $persister->update($entity);
1004
            }
1005
1006 107
            unset($this->entityUpdates[$oid]);
1007
1008 107
            if ($postUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
1009 107
                $this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke);
1010
            }
1011
        }
1012 107
    }
1013
1014
    /**
1015
     * Executes all entity deletions for entities of the specified type.
1016
     *
1017
     * @param ClassMetadata $class
1018
     */
1019 60
    private function executeDeletions($class)
1020
    {
1021 60
        $className = $class->getClassName();
1022 60
        $persister = $this->getEntityPersister($className);
1023 60
        $invoke    = $this->listenersInvoker->getSubscribedSystems($class, Events::postRemove);
1024
1025 60
        foreach ($this->entityDeletions as $oid => $entity) {
1026 60
            if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) {
1027 24
                continue;
1028
            }
1029
1030 60
            $persister->delete($entity);
1031
1032
            unset(
1033 60
                $this->entityDeletions[$oid],
1034 60
                $this->entityIdentifiers[$oid],
1035 60
                $this->originalEntityData[$oid],
1036 60
                $this->entityStates[$oid]
1037
            );
1038
1039
            // Entity with this $oid after deletion treated as NEW, even if the $oid
1040
            // is obtained by a new entity because the old one went out of scope.
1041 60
            if (! $class->isIdentifierComposite()) {
1042 57
                $property = $class->getProperty($class->getSingleIdentifierFieldName());
1043
1044 57
                if ($property instanceof FieldMetadata && $property->hasValueGenerator()) {
1045 50
                    $property->setValue($entity, null);
1046
                }
1047
            }
1048
1049 60
            if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1050 9
                $eventArgs = new LifecycleEventArgs($entity, $this->em);
1051
1052 60
                $this->listenersInvoker->invoke($class, Events::postRemove, $entity, $eventArgs, $invoke);
1053
            }
1054
        }
1055 59
    }
1056
1057
    /**
1058
     * Gets the commit order.
1059
     *
1060
     * @return ClassMetadata[]
1061
     */
1062 1009
    private function getCommitOrder()
1063
    {
1064 1009
        $calc = new Internal\CommitOrderCalculator();
1065
1066
        // See if there are any new classes in the changeset, that are not in the
1067
        // commit order graph yet (don't have a node).
1068
        // We have to inspect changeSet to be able to correctly build dependencies.
1069
        // It is not possible to use IdentityMap here because post inserted ids
1070
        // are not yet available.
1071 1009
        $newNodes = [];
1072
1073 1009
        foreach (array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions) as $entity) {
1074 1009
            $class = $this->em->getClassMetadata(get_class($entity));
1075
1076 1009
            if ($calc->hasNode($class->getClassName())) {
1077 635
                continue;
1078
            }
1079
1080 1009
            $calc->addNode($class->getClassName(), $class);
1081
1082 1009
            $newNodes[] = $class;
1083
        }
1084
1085
        // Calculate dependencies for new nodes
1086 1009
        while ($class = array_pop($newNodes)) {
1087 1009
            foreach ($class->getDeclaredPropertiesIterator() as $property) {
1088 1009
                if (! ($property instanceof ToOneAssociationMetadata && $property->isOwningSide())) {
1089 1009
                    continue;
1090
                }
1091
1092 834
                $targetClass = $this->em->getClassMetadata($property->getTargetEntity());
1093
1094 834
                if (! $calc->hasNode($targetClass->getClassName())) {
1095 637
                    $calc->addNode($targetClass->getClassName(), $targetClass);
1096
1097 637
                    $newNodes[] = $targetClass;
1098
                }
1099
1100 834
                $weight = ! array_filter(
1101 834
                    $property->getJoinColumns(),
1102
                    static function (JoinColumnMetadata $joinColumn) {
1103 834
                        return $joinColumn->isNullable();
1104 834
                    }
1105
                );
1106
1107 834
                $calc->addDependency($targetClass->getClassName(), $class->getClassName(), $weight);
1108
1109
                // If the target class has mapped subclasses, these share the same dependency.
1110 834
                if (! $targetClass->getSubClasses()) {
1111 829
                    continue;
1112
                }
1113
1114 225
                foreach ($targetClass->getSubClasses() as $subClassName) {
1115 225
                    $targetSubClass = $this->em->getClassMetadata($subClassName);
1116
1117 225
                    if (! $calc->hasNode($subClassName)) {
1118 199
                        $calc->addNode($targetSubClass->getClassName(), $targetSubClass);
1119
1120 199
                        $newNodes[] = $targetSubClass;
1121
                    }
1122
1123 225
                    $calc->addDependency($targetSubClass->getClassName(), $class->getClassName(), 1);
1124
                }
1125
            }
1126
        }
1127
1128 1009
        return $calc->sort();
1129
    }
1130
1131
    /**
1132
     * Schedules an entity for insertion into the database.
1133
     * If the entity already has an identifier, it will be added to the identity map.
1134
     *
1135
     * @param object $entity The entity to schedule for insertion.
1136
     *
1137
     * @throws ORMInvalidArgumentException
1138
     * @throws InvalidArgumentException
1139
     */
1140 1031
    public function scheduleForInsert($entity)
1141
    {
1142 1031
        $oid = spl_object_id($entity);
1143
1144 1031
        if (isset($this->entityUpdates[$oid])) {
1145
            throw new InvalidArgumentException('Dirty entity can not be scheduled for insertion.');
1146
        }
1147
1148 1031
        if (isset($this->entityDeletions[$oid])) {
1149 1
            throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
1150
        }
1151 1031
        if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
1152 1
            throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
1153
        }
1154
1155 1031
        if (isset($this->entityInsertions[$oid])) {
1156 1
            throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
1157
        }
1158
1159 1031
        $this->entityInsertions[$oid] = $entity;
1160
1161 1031
        if (isset($this->entityIdentifiers[$oid])) {
1162 221
            $this->addToIdentityMap($entity);
1163
        }
1164
1165 1031
        if ($entity instanceof NotifyPropertyChanged) {
1166 5
            $entity->addPropertyChangedListener($this);
1167
        }
1168 1031
    }
1169
1170
    /**
1171
     * Checks whether an entity is scheduled for insertion.
1172
     *
1173
     * @param object $entity
1174
     *
1175
     * @return bool
1176
     */
1177 621
    public function isScheduledForInsert($entity)
1178
    {
1179 621
        return isset($this->entityInsertions[spl_object_id($entity)]);
1180
    }
1181
1182
    /**
1183
     * Schedules an entity for being updated.
1184
     *
1185
     * @param object $entity The entity to schedule for being updated.
1186
     *
1187
     * @throws ORMInvalidArgumentException
1188
     */
1189 1
    public function scheduleForUpdate($entity) : void
1190
    {
1191 1
        $oid = spl_object_id($entity);
1192
1193 1
        if (! isset($this->entityIdentifiers[$oid])) {
1194
            throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'scheduling for update');
1195
        }
1196
1197 1
        if (isset($this->entityDeletions[$oid])) {
1198
            throw ORMInvalidArgumentException::entityIsRemoved($entity, 'schedule for update');
1199
        }
1200
1201 1
        if (! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
1202 1
            $this->entityUpdates[$oid] = $entity;
1203
        }
1204 1
    }
1205
1206
    /**
1207
     * INTERNAL:
1208
     * Schedules an extra update that will be executed immediately after the
1209
     * regular entity updates within the currently running commit cycle.
1210
     *
1211
     * Extra updates for entities are stored as (entity, changeset) tuples.
1212
     *
1213
     * @param object  $entity    The entity for which to schedule an extra update.
1214
     * @param mixed[] $changeset The changeset of the entity (what to update).
1215
     *
1216
     * @ignore
1217
     */
1218 29
    public function scheduleExtraUpdate($entity, array $changeset) : void
1219
    {
1220 29
        $oid         = spl_object_id($entity);
1221 29
        $extraUpdate = [$entity, $changeset];
1222
1223 29
        if (isset($this->extraUpdates[$oid])) {
1224 1
            [$unused, $changeset2] = $this->extraUpdates[$oid];
1225
1226 1
            $extraUpdate = [$entity, $changeset + $changeset2];
1227
        }
1228
1229 29
        $this->extraUpdates[$oid] = $extraUpdate;
1230 29
    }
1231
1232
    /**
1233
     * Checks whether an entity is registered as dirty in the unit of work.
1234
     * Note: Is not very useful currently as dirty entities are only registered
1235
     * at commit time.
1236
     *
1237
     * @param object $entity
1238
     */
1239
    public function isScheduledForUpdate($entity) : bool
1240
    {
1241
        return isset($this->entityUpdates[spl_object_id($entity)]);
1242
    }
1243
1244
    /**
1245
     * Checks whether an entity is registered to be checked in the unit of work.
1246
     *
1247
     * @param object $entity
1248
     */
1249 1
    public function isScheduledForDirtyCheck($entity) : bool
1250
    {
1251 1
        $rootEntityName = $this->em->getClassMetadata(get_class($entity))->getRootClassName();
1252
1253 1
        return isset($this->scheduledForSynchronization[$rootEntityName][spl_object_id($entity)]);
1254
    }
1255
1256
    /**
1257
     * INTERNAL:
1258
     * Schedules an entity for deletion.
1259
     *
1260
     * @param object $entity
1261
     */
1262 63
    public function scheduleForDelete($entity)
1263
    {
1264 63
        $oid = spl_object_id($entity);
1265
1266 63
        if (isset($this->entityInsertions[$oid])) {
1267 1
            if ($this->isInIdentityMap($entity)) {
1268
                $this->removeFromIdentityMap($entity);
1269
            }
1270
1271 1
            unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
1272
1273 1
            return; // entity has not been persisted yet, so nothing more to do.
1274
        }
1275
1276 63
        if (! $this->isInIdentityMap($entity)) {
1277 1
            return;
1278
        }
1279
1280 62
        $this->removeFromIdentityMap($entity);
1281
1282 62
        unset($this->entityUpdates[$oid]);
1283
1284 62
        if (! isset($this->entityDeletions[$oid])) {
1285 62
            $this->entityDeletions[$oid] = $entity;
1286 62
            $this->entityStates[$oid]    = self::STATE_REMOVED;
1287
        }
1288 62
    }
1289
1290
    /**
1291
     * Checks whether an entity is registered as removed/deleted with the unit
1292
     * of work.
1293
     *
1294
     * @param object $entity
1295
     *
1296
     * @return bool
1297
     */
1298 13
    public function isScheduledForDelete($entity)
1299
    {
1300 13
        return isset($this->entityDeletions[spl_object_id($entity)]);
1301
    }
1302
1303
    /**
1304
     * Checks whether an entity is scheduled for insertion, update or deletion.
1305
     *
1306
     * @param object $entity
1307
     *
1308
     * @return bool
1309
     */
1310
    public function isEntityScheduled($entity)
1311
    {
1312
        $oid = spl_object_id($entity);
1313
1314
        return isset($this->entityInsertions[$oid])
1315
            || isset($this->entityUpdates[$oid])
1316
            || isset($this->entityDeletions[$oid]);
1317
    }
1318
1319
    /**
1320
     * INTERNAL:
1321
     * Registers an entity in the identity map.
1322
     * Note that entities in a hierarchy are registered with the class name of
1323
     * the root entity.
1324
     *
1325
     * @param object $entity The entity to register.
1326
     *
1327
     * @return bool  TRUE if the registration was successful, FALSE if the identity of
1328
     *               the entity in question is already managed.
1329
     *
1330
     * @throws ORMInvalidArgumentException
1331
     *
1332
     * @ignore
1333
     */
1334 1099
    public function addToIdentityMap($entity)
1335
    {
1336 1099
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1337 1099
        $identifier    = $this->entityIdentifiers[spl_object_id($entity)];
1338
1339 1099
        if (empty($identifier) || in_array(null, $identifier, true)) {
1340 6
            throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->getClassName(), $entity);
1341
        }
1342
1343 1093
        $idHash    = implode(' ', $identifier);
1344 1093
        $className = $classMetadata->getRootClassName();
1345
1346 1093
        if (isset($this->identityMap[$className][$idHash])) {
1347 31
            return false;
1348
        }
1349
1350 1093
        $this->identityMap[$className][$idHash] = $entity;
1351
1352 1093
        return true;
1353
    }
1354
1355
    /**
1356
     * Gets the state of an entity with regard to the current unit of work.
1357
     *
1358
     * @param object   $entity
1359
     * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
1360
     *                         This parameter can be set to improve performance of entity state detection
1361
     *                         by potentially avoiding a database lookup if the distinction between NEW and DETACHED
1362
     *                         is either known or does not matter for the caller of the method.
1363
     *
1364
     * @return int The entity state.
1365
     */
1366 1039
    public function getEntityState($entity, $assume = null)
1367
    {
1368 1039
        $oid = spl_object_id($entity);
1369
1370 1039
        if (isset($this->entityStates[$oid])) {
1371 750
            return $this->entityStates[$oid];
1372
        }
1373
1374 1034
        if ($assume !== null) {
1375 1031
            return $assume;
1376
        }
1377
1378
        // State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
1379
        // Note that you can not remember the NEW or DETACHED state in _entityStates since
1380
        // the UoW does not hold references to such objects and the object hash can be reused.
1381
        // More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
1382 8
        $class     = $this->em->getClassMetadata(get_class($entity));
1383 8
        $persister = $this->getEntityPersister($class->getClassName());
1384 8
        $id        = $persister->getIdentifier($entity);
1385
1386 8
        if (! $id) {
1387 3
            return self::STATE_NEW;
1388
        }
1389
1390 6
        $flatId = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $id);
1391
1392 6
        if ($class->isIdentifierComposite()
1393 5
            || ! $class->getProperty($class->getSingleIdentifierFieldName()) instanceof FieldMetadata
1394 6
            || ! $class->getProperty($class->getSingleIdentifierFieldName())->hasValueGenerator()
1395
        ) {
1396
            // Check for a version field, if available, to avoid a db lookup.
1397 5
            if ($class->isVersioned()) {
1398 1
                return $class->versionProperty->getValue($entity)
1399
                    ? self::STATE_DETACHED
1400 1
                    : self::STATE_NEW;
1401
            }
1402
1403
            // Last try before db lookup: check the identity map.
1404 4
            if ($this->tryGetById($flatId, $class->getRootClassName())) {
1405 1
                return self::STATE_DETACHED;
1406
            }
1407
1408
            // db lookup
1409 4
            if ($this->getEntityPersister($class->getClassName())->exists($entity)) {
1410
                return self::STATE_DETACHED;
1411
            }
1412
1413 4
            return self::STATE_NEW;
1414
        }
1415
1416 1
        if ($class->isIdentifierComposite()
1417 1
            || ! $class->getProperty($class->getSingleIdentifierFieldName()) instanceof FieldMetadata
1418 1
            || ! $class->getValueGenerationPlan()->containsDeferred()) {
1419
            // if we have a pre insert generator we can't be sure that having an id
1420
            // really means that the entity exists. We have to verify this through
1421
            // the last resort: a db lookup
1422
1423
            // Last try before db lookup: check the identity map.
1424
            if ($this->tryGetById($flatId, $class->getRootClassName())) {
1425
                return self::STATE_DETACHED;
1426
            }
1427
1428
            // db lookup
1429
            if ($this->getEntityPersister($class->getClassName())->exists($entity)) {
1430
                return self::STATE_DETACHED;
1431
            }
1432
1433
            return self::STATE_NEW;
1434
        }
1435
1436 1
        return self::STATE_DETACHED;
1437
    }
1438
1439
    /**
1440
     * INTERNAL:
1441
     * Removes an entity from the identity map. This effectively detaches the
1442
     * entity from the persistence management of Doctrine.
1443
     *
1444
     * @param object $entity
1445
     *
1446
     * @return bool
1447
     *
1448
     * @throws ORMInvalidArgumentException
1449
     *
1450
     * @ignore
1451
     */
1452 62
    public function removeFromIdentityMap($entity)
1453
    {
1454 62
        $oid           = spl_object_id($entity);
1455 62
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1456 62
        $idHash        = implode(' ', $this->entityIdentifiers[$oid]);
1457
1458 62
        if ($idHash === '') {
1459
            throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'remove from identity map');
1460
        }
1461
1462 62
        $className = $classMetadata->getRootClassName();
1463
1464 62
        if (isset($this->identityMap[$className][$idHash])) {
1465 62
            unset($this->identityMap[$className][$idHash], $this->readOnlyObjects[$oid]);
1466
1467 62
            return true;
1468
        }
1469
1470
        return false;
1471
    }
1472
1473
    /**
1474
     * INTERNAL:
1475
     * Gets an entity in the identity map by its identifier hash.
1476
     *
1477
     * @param string $idHash
1478
     * @param string $rootClassName
1479
     *
1480
     * @return object
1481
     *
1482
     * @ignore
1483
     */
1484 6
    public function getByIdHash($idHash, $rootClassName)
1485
    {
1486 6
        return $this->identityMap[$rootClassName][$idHash];
1487
    }
1488
1489
    /**
1490
     * INTERNAL:
1491
     * Tries to get an entity by its identifier hash. If no entity is found for
1492
     * the given hash, FALSE is returned.
1493
     *
1494
     * @param mixed  $idHash        (must be possible to cast it to string)
1495
     * @param string $rootClassName
1496
     *
1497
     * @return object|bool The found entity or FALSE.
1498
     *
1499
     * @ignore
1500
     */
1501
    public function tryGetByIdHash($idHash, $rootClassName)
1502
    {
1503
        $stringIdHash = (string) $idHash;
1504
1505
        return $this->identityMap[$rootClassName][$stringIdHash] ?? false;
1506
    }
1507
1508
    /**
1509
     * Checks whether an entity is registered in the identity map of this UnitOfWork.
1510
     *
1511
     * @param object $entity
1512
     *
1513
     * @return bool
1514
     */
1515 147
    public function isInIdentityMap($entity)
1516
    {
1517 147
        $oid = spl_object_id($entity);
1518
1519 147
        if (empty($this->entityIdentifiers[$oid])) {
1520 23
            return false;
1521
        }
1522
1523 133
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1524 133
        $idHash        = implode(' ', $this->entityIdentifiers[$oid]);
1525
1526 133
        return isset($this->identityMap[$classMetadata->getRootClassName()][$idHash]);
1527
    }
1528
1529
    /**
1530
     * INTERNAL:
1531
     * Checks whether an identifier hash exists in the identity map.
1532
     *
1533
     * @param string $idHash
1534
     * @param string $rootClassName
1535
     *
1536
     * @return bool
1537
     *
1538
     * @ignore
1539
     */
1540
    public function containsIdHash($idHash, $rootClassName)
1541
    {
1542
        return isset($this->identityMap[$rootClassName][$idHash]);
1543
    }
1544
1545
    /**
1546
     * Persists an entity as part of the current unit of work.
1547
     *
1548
     * @param object $entity The entity to persist.
1549
     */
1550 1031
    public function persist($entity)
1551
    {
1552 1031
        $visited = [];
1553
1554 1031
        $this->doPersist($entity, $visited);
1555 1024
    }
1556
1557
    /**
1558
     * Persists an entity as part of the current unit of work.
1559
     *
1560
     * This method is internally called during persist() cascades as it tracks
1561
     * the already visited entities to prevent infinite recursions.
1562
     *
1563
     * @param object   $entity  The entity to persist.
1564
     * @param object[] $visited The already visited entities.
1565
     *
1566
     * @throws ORMInvalidArgumentException
1567
     * @throws UnexpectedValueException
1568
     */
1569 1031
    private function doPersist($entity, array &$visited)
1570
    {
1571 1031
        $oid = spl_object_id($entity);
1572
1573 1031
        if (isset($visited[$oid])) {
1574 109
            return; // Prevent infinite recursion
1575
        }
1576
1577 1031
        $visited[$oid] = $entity; // Mark visited
1578
1579 1031
        $class = $this->em->getClassMetadata(get_class($entity));
1580
1581
        // We assume NEW, so DETACHED entities result in an exception on flush (constraint violation).
1582
        // If we would detect DETACHED here we would throw an exception anyway with the same
1583
        // consequences (not recoverable/programming error), so just assuming NEW here
1584
        // lets us avoid some database lookups for entities with natural identifiers.
1585 1031
        $entityState = $this->getEntityState($entity, self::STATE_NEW);
1586
1587
        switch ($entityState) {
1588 1031
            case self::STATE_MANAGED:
1589
                // Nothing to do, except if policy is "deferred explicit"
1590 219
                if ($class->changeTrackingPolicy === ChangeTrackingPolicy::DEFERRED_EXPLICIT) {
1591 2
                    $this->scheduleForSynchronization($entity);
1592
                }
1593 219
                break;
1594
1595 1031
            case self::STATE_NEW:
1596 1030
                $this->persistNew($class, $entity);
1597 1030
                break;
1598
1599 1
            case self::STATE_REMOVED:
1600
                // Entity becomes managed again
1601 1
                unset($this->entityDeletions[$oid]);
1602 1
                $this->addToIdentityMap($entity);
1603
1604 1
                $this->entityStates[$oid] = self::STATE_MANAGED;
1605 1
                break;
1606
1607
            case self::STATE_DETACHED:
1608
                // Can actually not happen right now since we assume STATE_NEW.
1609
                throw ORMInvalidArgumentException::detachedEntityCannot($entity, 'persisted');
1610
1611
            default:
1612
                throw new UnexpectedValueException(
1613
                    sprintf('Unexpected entity state: %d.%s', $entityState, self::objToStr($entity))
1614
                );
1615
        }
1616
1617 1031
        $this->cascadePersist($entity, $visited);
1618 1024
    }
1619
1620
    /**
1621
     * Deletes an entity as part of the current unit of work.
1622
     *
1623
     * @param object $entity The entity to remove.
1624
     */
1625 62
    public function remove($entity)
1626
    {
1627 62
        $visited = [];
1628
1629 62
        $this->doRemove($entity, $visited);
1630 62
    }
1631
1632
    /**
1633
     * Deletes an entity as part of the current unit of work.
1634
     *
1635
     * This method is internally called during delete() cascades as it tracks
1636
     * the already visited entities to prevent infinite recursions.
1637
     *
1638
     * @param object   $entity  The entity to delete.
1639
     * @param object[] $visited The map of the already visited entities.
1640
     *
1641
     * @throws ORMInvalidArgumentException If the instance is a detached entity.
1642
     * @throws UnexpectedValueException
1643
     */
1644 62
    private function doRemove($entity, array &$visited)
1645
    {
1646 62
        $oid = spl_object_id($entity);
1647
1648 62
        if (isset($visited[$oid])) {
1649 1
            return; // Prevent infinite recursion
1650
        }
1651
1652 62
        $visited[$oid] = $entity; // mark visited
1653
1654
        // Cascade first, because scheduleForDelete() removes the entity from the identity map, which
1655
        // can cause problems when a lazy proxy has to be initialized for the cascade operation.
1656 62
        $this->cascadeRemove($entity, $visited);
1657
1658 62
        $class       = $this->em->getClassMetadata(get_class($entity));
1659 62
        $entityState = $this->getEntityState($entity);
1660
1661
        switch ($entityState) {
1662 62
            case self::STATE_NEW:
1663 62
            case self::STATE_REMOVED:
1664
                // nothing to do
1665 2
                break;
1666
1667 62
            case self::STATE_MANAGED:
1668 62
                $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preRemove);
1669
1670 62
                if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1671 8
                    $this->listenersInvoker->invoke($class, Events::preRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
1672
                }
1673
1674 62
                $this->scheduleForDelete($entity);
1675 62
                break;
1676
1677
            case self::STATE_DETACHED:
1678
                throw ORMInvalidArgumentException::detachedEntityCannot($entity, 'removed');
1679
            default:
1680
                throw new UnexpectedValueException(
1681
                    sprintf('Unexpected entity state: %d.%s', $entityState, self::objToStr($entity))
1682
                );
1683
        }
1684 62
    }
1685
1686
    /**
1687
     * Refreshes the state of the given entity from the database, overwriting
1688
     * any local, unpersisted changes.
1689
     *
1690
     * @param object $entity The entity to refresh.
1691
     *
1692
     * @throws InvalidArgumentException If the entity is not MANAGED.
1693
     */
1694 15
    public function refresh($entity)
1695
    {
1696 15
        $visited = [];
1697
1698 15
        $this->doRefresh($entity, $visited);
1699 15
    }
1700
1701
    /**
1702
     * Executes a refresh operation on an entity.
1703
     *
1704
     * @param object   $entity  The entity to refresh.
1705
     * @param object[] $visited The already visited entities during cascades.
1706
     *
1707
     * @throws ORMInvalidArgumentException If the entity is not MANAGED.
1708
     */
1709 15
    private function doRefresh($entity, array &$visited)
1710
    {
1711 15
        $oid = spl_object_id($entity);
1712
1713 15
        if (isset($visited[$oid])) {
1714
            return; // Prevent infinite recursion
1715
        }
1716
1717 15
        $visited[$oid] = $entity; // mark visited
1718
1719 15
        $class = $this->em->getClassMetadata(get_class($entity));
1720
1721 15
        if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
1722
            throw ORMInvalidArgumentException::entityNotManaged($entity);
1723
        }
1724
1725 15
        $this->getEntityPersister($class->getClassName())->refresh(
1726 15
            array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
1727 15
            $entity
1728
        );
1729
1730 15
        $this->cascadeRefresh($entity, $visited);
1731 15
    }
1732
1733
    /**
1734
     * Cascades a refresh operation to associated entities.
1735
     *
1736
     * @param object   $entity
1737
     * @param object[] $visited
1738
     */
1739 15
    private function cascadeRefresh($entity, array &$visited)
1740
    {
1741 15
        $class = $this->em->getClassMetadata(get_class($entity));
1742
1743 15
        foreach ($class->getDeclaredPropertiesIterator() as $association) {
1744 15
            if (! ($association instanceof AssociationMetadata && in_array('refresh', $association->getCascade(), true))) {
1745 15
                continue;
1746
            }
1747
1748 4
            $relatedEntities = $association->getValue($entity);
1749
1750
            switch (true) {
1751 4
                case $relatedEntities instanceof PersistentCollection:
1752
                    // Unwrap so that foreach() does not initialize
1753 4
                    $relatedEntities = $relatedEntities->unwrap();
1754
                    // break; is commented intentionally!
1755
1756
                case $relatedEntities instanceof Collection:
1757
                case is_array($relatedEntities):
1758 4
                    foreach ($relatedEntities as $relatedEntity) {
1759
                        $this->doRefresh($relatedEntity, $visited);
1760
                    }
1761 4
                    break;
1762
1763
                case $relatedEntities !== null:
1764
                    $this->doRefresh($relatedEntities, $visited);
1765
                    break;
1766
1767 4
                default:
1768
                    // Do nothing
1769
            }
1770
        }
1771 15
    }
1772
1773
    /**
1774
     * Cascades the save operation to associated entities.
1775
     *
1776
     * @param object   $entity
1777
     * @param object[] $visited
1778
     *
1779
     * @throws ORMInvalidArgumentException
1780
     */
1781 1031
    private function cascadePersist($entity, array &$visited)
1782
    {
1783 1031
        $class = $this->em->getClassMetadata(get_class($entity));
1784
1785 1031
        if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
1786
            // nothing to do - proxy is not initialized, therefore we don't do anything with it
1787 1
            return;
1788
        }
1789
1790 1031
        foreach ($class->getDeclaredPropertiesIterator() as $association) {
1791 1031
            if (! ($association instanceof AssociationMetadata && in_array('persist', $association->getCascade(), true))) {
1792 1031
                continue;
1793
            }
1794
1795
            /** @var AssociationMetadata $association */
1796 647
            $relatedEntities = $association->getValue($entity);
1797 647
            $targetEntity    = $association->getTargetEntity();
1798
1799
            switch (true) {
1800 647
                case $relatedEntities instanceof PersistentCollection:
1801
                    // Unwrap so that foreach() does not initialize
1802 13
                    $relatedEntities = $relatedEntities->unwrap();
1803
                    // break; is commented intentionally!
1804
1805 647
                case $relatedEntities instanceof Collection:
1806 584
                case is_array($relatedEntities):
1807 542
                    if (! ($association instanceof ToManyAssociationMetadata)) {
1808 3
                        throw ORMInvalidArgumentException::invalidAssociation(
1809 3
                            $this->em->getClassMetadata($targetEntity),
1810 3
                            $association,
1811 3
                            $relatedEntities
1812
                        );
1813
                    }
1814
1815 539
                    foreach ($relatedEntities as $relatedEntity) {
1816 283
                        $this->doPersist($relatedEntity, $visited);
1817
                    }
1818
1819 539
                    break;
1820
1821 573
                case $relatedEntities !== null:
1822 241
                    if (! $relatedEntities instanceof $targetEntity) {
1823 4
                        throw ORMInvalidArgumentException::invalidAssociation(
1824 4
                            $this->em->getClassMetadata($targetEntity),
1825 4
                            $association,
1826 4
                            $relatedEntities
1827
                        );
1828
                    }
1829
1830 237
                    $this->doPersist($relatedEntities, $visited);
1831 237
                    break;
1832
1833 641
                default:
1834
                    // Do nothing
1835
            }
1836
        }
1837 1024
    }
1838
1839
    /**
1840
     * Cascades the delete operation to associated entities.
1841
     *
1842
     * @param object   $entity
1843
     * @param object[] $visited
1844
     */
1845 62
    private function cascadeRemove($entity, array &$visited)
1846
    {
1847 62
        $entitiesToCascade = [];
1848 62
        $class             = $this->em->getClassMetadata(get_class($entity));
1849
1850 62
        foreach ($class->getDeclaredPropertiesIterator() as $association) {
1851 62
            if (! ($association instanceof AssociationMetadata && in_array('remove', $association->getCascade(), true))) {
1852 62
                continue;
1853
            }
1854
1855 25
            if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
1856 6
                $entity->initializeProxy();
1857
            }
1858
1859 25
            $relatedEntities = $association->getValue($entity);
1860
1861
            switch (true) {
1862 25
                case $relatedEntities instanceof Collection:
1863 18
                case is_array($relatedEntities):
1864
                    // If its a PersistentCollection initialization is intended! No unwrap!
1865 20
                    foreach ($relatedEntities as $relatedEntity) {
1866 10
                        $entitiesToCascade[] = $relatedEntity;
1867
                    }
1868 20
                    break;
1869
1870 18
                case $relatedEntities !== null:
1871 7
                    $entitiesToCascade[] = $relatedEntities;
1872 7
                    break;
1873
1874 25
                default:
1875
                    // Do nothing
1876
            }
1877
        }
1878
1879 62
        foreach ($entitiesToCascade as $relatedEntity) {
1880 16
            $this->doRemove($relatedEntity, $visited);
1881
        }
1882 62
    }
1883
1884
    /**
1885
     * Acquire a lock on the given entity.
1886
     *
1887
     * @param object $entity
1888
     * @param int    $lockMode
1889
     * @param int    $lockVersion
1890
     *
1891
     * @throws ORMInvalidArgumentException
1892
     * @throws TransactionRequiredException
1893
     * @throws OptimisticLockException
1894
     * @throws InvalidArgumentException
1895
     */
1896 10
    public function lock($entity, $lockMode, $lockVersion = null)
1897
    {
1898 10
        if ($entity === null) {
1899 1
            throw new InvalidArgumentException('No entity passed to UnitOfWork#lock().');
1900
        }
1901
1902 9
        if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) {
1903 1
            throw ORMInvalidArgumentException::entityNotManaged($entity);
1904
        }
1905
1906 8
        $class = $this->em->getClassMetadata(get_class($entity));
1907
1908
        switch (true) {
1909 8
            case $lockMode === LockMode::OPTIMISTIC:
1910 6
                if (! $class->isVersioned()) {
1911 1
                    throw OptimisticLockException::notVersioned($class->getClassName());
1912
                }
1913
1914 5
                if ($lockVersion === null) {
1915 1
                    return;
1916
                }
1917
1918 4
                if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
1919 1
                    $entity->initializeProxy();
1920
                }
1921
1922 4
                $entityVersion = $class->versionProperty->getValue($entity);
1923
1924 4
                if ($entityVersion !== $lockVersion) {
1925 2
                    throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion);
1926
                }
1927
1928 2
                break;
1929
1930 2
            case $lockMode === LockMode::NONE:
1931 2
            case $lockMode === LockMode::PESSIMISTIC_READ:
1932 1
            case $lockMode === LockMode::PESSIMISTIC_WRITE:
1933 2
                if (! $this->em->getConnection()->isTransactionActive()) {
1934 2
                    throw TransactionRequiredException::transactionRequired();
1935
                }
1936
1937
                $oid = spl_object_id($entity);
1938
1939
                $this->getEntityPersister($class->getClassName())->lock(
1940
                    array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
1941
                    $lockMode
1942
                );
1943
                break;
1944
1945
            default:
1946
                // Do nothing
1947
        }
1948 2
    }
1949
1950
    /**
1951
     * Clears the UnitOfWork.
1952
     */
1953 1208
    public function clear()
1954
    {
1955 1208
        $this->entityPersisters               =
1956 1208
        $this->collectionPersisters           =
1957 1208
        $this->eagerLoadingEntities           =
1958 1208
        $this->identityMap                    =
1959 1208
        $this->entityIdentifiers              =
1960 1208
        $this->originalEntityData             =
1961 1208
        $this->entityChangeSets               =
1962 1208
        $this->entityStates                   =
1963 1208
        $this->scheduledForSynchronization    =
1964 1208
        $this->entityInsertions               =
1965 1208
        $this->entityUpdates                  =
1966 1208
        $this->entityDeletions                =
1967 1208
        $this->collectionDeletions            =
1968 1208
        $this->collectionUpdates              =
1969 1208
        $this->extraUpdates                   =
1970 1208
        $this->readOnlyObjects                =
1971 1208
        $this->visitedCollections             =
1972 1208
        $this->nonCascadedNewDetectedEntities =
1973 1208
        $this->orphanRemovals                 = [];
1974 1208
    }
1975
1976
    /**
1977
     * INTERNAL:
1978
     * Schedules an orphaned entity for removal. The remove() operation will be
1979
     * invoked on that entity at the beginning of the next commit of this
1980
     * UnitOfWork.
1981
     *
1982
     * @param object $entity
1983
     *
1984
     * @ignore
1985
     */
1986 16
    public function scheduleOrphanRemoval($entity)
1987
    {
1988 16
        $this->orphanRemovals[spl_object_id($entity)] = $entity;
1989 16
    }
1990
1991
    /**
1992
     * INTERNAL:
1993
     * Cancels a previously scheduled orphan removal.
1994
     *
1995
     * @param object $entity
1996
     *
1997
     * @ignore
1998
     */
1999 111
    public function cancelOrphanRemoval($entity)
2000
    {
2001 111
        unset($this->orphanRemovals[spl_object_id($entity)]);
2002 111
    }
2003
2004
    /**
2005
     * INTERNAL:
2006
     * Schedules a complete collection for removal when this UnitOfWork commits.
2007
     */
2008 22
    public function scheduleCollectionDeletion(PersistentCollection $coll)
2009
    {
2010 22
        $coid = spl_object_id($coll);
2011
2012
        // TODO: if $coll is already scheduled for recreation ... what to do?
2013
        // Just remove $coll from the scheduled recreations?
2014 22
        unset($this->collectionUpdates[$coid]);
2015
2016 22
        $this->collectionDeletions[$coid] = $coll;
2017 22
    }
2018
2019
    /**
2020
     * @return bool
2021
     */
2022 8
    public function isCollectionScheduledForDeletion(PersistentCollection $coll)
2023
    {
2024 8
        return isset($this->collectionDeletions[spl_object_id($coll)]);
2025
    }
2026
2027
    /**
2028
     * INTERNAL:
2029
     * Creates a new instance of the mapped class, without invoking the constructor.
2030
     * This is only meant to be used internally, and should not be consumed by end users.
2031
     *
2032
     * @return EntityManagerAware|object
2033
     *
2034
     * @ignore
2035
     */
2036 665
    public function newInstance(ClassMetadata $class)
2037
    {
2038 665
        $entity = $this->instantiator->instantiate($class->getClassName());
2039
2040 665
        if ($entity instanceof EntityManagerAware) {
2041 5
            $entity->injectEntityManager($this->em, $class);
2042
        }
2043
2044 665
        return $entity;
2045
    }
2046
2047
    /**
2048
     * INTERNAL:
2049
     * Creates an entity. Used for reconstitution of persistent entities.
2050
     *
2051
     * {@internal Highly performance-sensitive method. }}
2052
     *
2053
     * @param string  $className The name of the entity class.
2054
     * @param mixed[] $data      The data for the entity.
2055
     * @param mixed[] $hints     Any hints to account for during reconstitution/lookup of the entity.
2056
     *
2057
     * @return object The managed entity instance.
2058
     *
2059
     * @ignore
2060
     * @todo Rename: getOrCreateEntity
2061
     */
2062 802
    public function createEntity($className, array $data, &$hints = [])
2063
    {
2064 802
        $class  = $this->em->getClassMetadata($className);
2065 802
        $id     = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $data);
2066 802
        $idHash = implode(' ', $id);
2067
2068 802
        if (isset($this->identityMap[$class->getRootClassName()][$idHash])) {
2069 305
            $entity = $this->identityMap[$class->getRootClassName()][$idHash];
2070 305
            $oid    = spl_object_id($entity);
2071
2072 305
            if (isset($hints[Query::HINT_REFRESH], $hints[Query::HINT_REFRESH_ENTITY])) {
2073 65
                $unmanagedProxy = $hints[Query::HINT_REFRESH_ENTITY];
2074 65
                if ($unmanagedProxy !== $entity
2075 65
                    && $unmanagedProxy instanceof GhostObjectInterface
2076 65
                    && $this->isIdentifierEquals($unmanagedProxy, $entity)
2077
                ) {
2078
                    // We will hydrate the given un-managed proxy anyway:
2079
                    // continue work, but consider it the entity from now on
2080 5
                    $entity = $unmanagedProxy;
2081
                }
2082
            }
2083
2084 305
            if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
2085 21
                $entity->setProxyInitializer(null);
2086
2087 21
                if ($entity instanceof NotifyPropertyChanged) {
2088 21
                    $entity->addPropertyChangedListener($this);
2089
                }
2090
            } else {
2091 291
                if (! isset($hints[Query::HINT_REFRESH])
2092 291
                    || (isset($hints[Query::HINT_REFRESH_ENTITY]) && $hints[Query::HINT_REFRESH_ENTITY] !== $entity)) {
2093 229
                    return $entity;
2094
                }
2095
            }
2096
2097
            // inject EntityManager upon refresh.
2098 103
            if ($entity instanceof EntityManagerAware) {
2099 3
                $entity->injectEntityManager($this->em, $class);
0 ignored issues
show
$class of type Doctrine\Common\Persistence\Mapping\ClassMetadata is incompatible with the type Doctrine\ORM\Mapping\ClassMetadata expected by parameter $classMetadata of Doctrine\ORM\EntityManag...::injectEntityManager(). ( Ignorable by Annotation )

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

2099
                $entity->injectEntityManager($this->em, /** @scrutinizer ignore-type */ $class);
Loading history...
2100
            }
2101
2102 103
            $this->originalEntityData[$oid] = $data;
2103
        } else {
2104 662
            $entity = $this->newInstance($class);
2105 662
            $oid    = spl_object_id($entity);
2106
2107 662
            $this->entityIdentifiers[$oid]  = $id;
2108 662
            $this->entityStates[$oid]       = self::STATE_MANAGED;
2109 662
            $this->originalEntityData[$oid] = $data;
2110
2111 662
            $this->identityMap[$class->getRootClassName()][$idHash] = $entity;
2112
        }
2113
2114 695
        if ($entity instanceof NotifyPropertyChanged) {
2115 3
            $entity->addPropertyChangedListener($this);
2116
        }
2117
2118 695
        foreach ($data as $field => $value) {
2119 695
            $property = $class->getProperty($field);
2120
2121 695
            if ($property instanceof FieldMetadata) {
2122 695
                $property->setValue($entity, $value);
2123
            }
2124
        }
2125
2126
        // Loading the entity right here, if its in the eager loading map get rid of it there.
2127 695
        unset($this->eagerLoadingEntities[$class->getRootClassName()][$idHash]);
2128
2129 695
        if (isset($this->eagerLoadingEntities[$class->getRootClassName()]) && ! $this->eagerLoadingEntities[$class->getRootClassName()]) {
2130
            unset($this->eagerLoadingEntities[$class->getRootClassName()]);
2131
        }
2132
2133
        // Properly initialize any unfetched associations, if partial objects are not allowed.
2134 695
        if (isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
2135 34
            return $entity;
2136
        }
2137
2138 661
        foreach ($class->getDeclaredPropertiesIterator() as $field => $association) {
2139 661
            if (! ($association instanceof AssociationMetadata)) {
2140 661
                continue;
2141
            }
2142
2143
            // Check if the association is not among the fetch-joined associations already.
2144 566
            if (isset($hints['fetchAlias'], $hints['fetched'][$hints['fetchAlias']][$field])) {
2145 243
                continue;
2146
            }
2147
2148 543
            $targetEntity = $association->getTargetEntity();
2149 543
            $targetClass  = $this->em->getClassMetadata($targetEntity);
2150
2151 543
            if ($association instanceof ToManyAssociationMetadata) {
2152
                // Ignore if its a cached collection
2153 464
                if (isset($hints[Query::HINT_CACHE_ENABLED]) &&
2154 464
                    $association->getValue($entity) instanceof PersistentCollection) {
2155
                    continue;
2156
                }
2157
2158 464
                $hasDataField = isset($data[$field]);
2159
2160
                // use the given collection
2161 464
                if ($hasDataField && $data[$field] instanceof PersistentCollection) {
2162
                    $data[$field]->setOwner($entity, $association);
2163
2164
                    $association->setValue($entity, $data[$field]);
2165
2166
                    $this->originalEntityData[$oid][$field] = $data[$field];
2167
2168
                    continue;
2169
                }
2170
2171
                // Inject collection
2172 464
                $pColl = $association->wrap($entity, $hasDataField ? $data[$field] : [], $this->em);
2173
2174 464
                $pColl->setInitialized($hasDataField);
2175
2176 464
                $association->setValue($entity, $pColl);
2177
2178 464
                if ($association->getFetchMode() === FetchMode::EAGER) {
2179 4
                    $this->loadCollection($pColl);
2180 4
                    $pColl->takeSnapshot();
2181
                }
2182
2183 464
                $this->originalEntityData[$oid][$field] = $pColl;
2184
2185 464
                continue;
2186
            }
2187
2188 470
            if (! $association->isOwningSide()) {
2189
                // use the given entity association
2190 67
                if (isset($data[$field]) && is_object($data[$field]) &&
2191 67
                    isset($this->entityStates[spl_object_id($data[$field])])) {
2192 3
                    $inverseAssociation = $targetClass->getProperty($association->getMappedBy());
2193
2194 3
                    $association->setValue($entity, $data[$field]);
2195 3
                    $inverseAssociation->setValue($data[$field], $entity);
2196
2197 3
                    $this->originalEntityData[$oid][$field] = $data[$field];
2198
2199 3
                    continue;
2200
                }
2201
2202
                // Inverse side of x-to-one can never be lazy
2203 64
                $persister = $this->getEntityPersister($targetEntity);
2204
2205 64
                $association->setValue($entity, $persister->loadToOneEntity($association, $entity));
2206
2207 64
                continue;
2208
            }
2209
2210
            // use the entity association
2211 470
            if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_id($data[$field])])) {
2212 38
                $association->setValue($entity, $data[$field]);
2213
2214 38
                $this->originalEntityData[$oid][$field] = $data[$field];
2215
2216 38
                continue;
2217
            }
2218
2219 463
            $associatedId = [];
2220
2221
            // TODO: Is this even computed right in all cases of composite keys?
2222 463
            foreach ($association->getJoinColumns() as $joinColumn) {
2223
                /** @var JoinColumnMetadata $joinColumn */
2224 463
                $joinColumnName  = $joinColumn->getColumnName();
2225 463
                $joinColumnValue = $data[$joinColumnName] ?? null;
2226 463
                $targetField     = $targetClass->fieldNames[$joinColumn->getReferencedColumnName()];
2227
2228 463
                if ($joinColumnValue === null && in_array($targetField, $targetClass->identifier, true)) {
2229
                    // the missing key is part of target's entity primary key
2230 267
                    $associatedId = [];
2231
2232 267
                    continue;
2233
                }
2234
2235 284
                $associatedId[$targetField] = $joinColumnValue;
2236
            }
2237
2238 463
            if (! $associatedId) {
2239
                // Foreign key is NULL
2240 267
                $association->setValue($entity, null);
2241 267
                $this->originalEntityData[$oid][$field] = null;
2242
2243 267
                continue;
2244
            }
2245
2246
            // @todo guilhermeblanco Can we remove the need of this somehow?
2247 284
            if (! isset($hints['fetchMode'][$class->getClassName()][$field])) {
2248 281
                $hints['fetchMode'][$class->getClassName()][$field] = $association->getFetchMode();
2249
            }
2250
2251
            // Foreign key is set
2252
            // Check identity map first
2253
            // FIXME: Can break easily with composite keys if join column values are in
2254
            //        wrong order. The correct order is the one in ClassMetadata#identifier.
2255 284
            $relatedIdHash = implode(' ', $associatedId);
2256
2257
            switch (true) {
2258 284
                case isset($this->identityMap[$targetClass->getRootClassName()][$relatedIdHash]):
2259 168
                    $newValue = $this->identityMap[$targetClass->getRootClassName()][$relatedIdHash];
2260
2261
                    // If this is an uninitialized proxy, we are deferring eager loads,
2262
                    // this association is marked as eager fetch, and its an uninitialized proxy (wtf!)
2263
                    // then we can append this entity for eager loading!
2264 168
                    if (! $targetClass->isIdentifierComposite() &&
2265 168
                        $newValue instanceof GhostObjectInterface &&
2266 168
                        isset($hints[self::HINT_DEFEREAGERLOAD]) &&
2267 168
                        $hints['fetchMode'][$class->getClassName()][$field] === FetchMode::EAGER &&
2268 168
                        ! $newValue->isProxyInitialized()
2269
                    ) {
2270
                        $this->eagerLoadingEntities[$targetClass->getRootClassName()][$relatedIdHash] = current($associatedId);
2271
                    }
2272
2273 168
                    break;
2274
2275 190
                case $targetClass->getSubClasses():
2276
                    // If it might be a subtype, it can not be lazy. There isn't even
2277
                    // a way to solve this with deferred eager loading, which means putting
2278
                    // an entity with subclasses at a *-to-one location is really bad! (performance-wise)
2279 29
                    $persister = $this->getEntityPersister($targetEntity);
2280 29
                    $newValue  = $persister->loadToOneEntity($association, $entity, $associatedId);
2281 29
                    break;
2282
2283
                default:
2284
                    // Proxies do not carry any kind of original entity data until they're fully loaded/initialized
2285 163
                    $managedData = [];
2286
2287 163
                    $normalizedAssociatedId = $this->normalizeIdentifier->__invoke(
2288 163
                        $this->em,
2289 163
                        $targetClass,
0 ignored issues
show
$targetClass of type Doctrine\Common\Persistence\Mapping\ClassMetadata is incompatible with the type Doctrine\ORM\Mapping\ClassMetadata expected by parameter $targetClass of Doctrine\ORM\Utility\Nor...eIdentifier::__invoke(). ( Ignorable by Annotation )

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

2289
                        /** @scrutinizer ignore-type */ $targetClass,
Loading history...
2290 163
                        $associatedId
2291
                    );
2292
2293
                    switch (true) {
2294
                        // We are negating the condition here. Other cases will assume it is valid!
2295 163
                        case $hints['fetchMode'][$class->getClassName()][$field] !== FetchMode::EAGER:
2296 156
                            $newValue = $this->em->getProxyFactory()->getProxy($targetClass, $normalizedAssociatedId);
0 ignored issues
show
$targetClass of type Doctrine\Common\Persistence\Mapping\ClassMetadata is incompatible with the type Doctrine\ORM\Mapping\ClassMetadata expected by parameter $metadata of Doctrine\ORM\Proxy\Facto...roxyFactory::getProxy(). ( Ignorable by Annotation )

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

2296
                            $newValue = $this->em->getProxyFactory()->getProxy(/** @scrutinizer ignore-type */ $targetClass, $normalizedAssociatedId);
Loading history...
2297 156
                            break;
2298
2299
                        // Deferred eager load only works for single identifier classes
2300 7
                        case isset($hints[self::HINT_DEFEREAGERLOAD]) && ! $targetClass->isIdentifierComposite():
2301
                            // TODO: Is there a faster approach?
2302 7
                            $this->eagerLoadingEntities[$targetClass->getRootClassName()][$relatedIdHash] = current($normalizedAssociatedId);
2303
2304 7
                            $newValue = $this->em->getProxyFactory()->getProxy($targetClass, $normalizedAssociatedId);
2305 7
                            break;
2306
2307
                        default:
2308
                            // TODO: This is very imperformant, ignore it?
2309
                            $newValue = $this->em->find($targetEntity, $normalizedAssociatedId);
2310
                            // Needed to re-assign original entity data for freshly loaded entity
2311
                            $managedData = $this->originalEntityData[spl_object_id($newValue)];
2312
                            break;
2313
                    }
2314
2315
                    // @TODO using `$associatedId` here seems to be risky.
2316 163
                    $this->registerManaged($newValue, $associatedId, $managedData);
2317
2318 163
                    break;
2319
            }
2320
2321 284
            $this->originalEntityData[$oid][$field] = $newValue;
2322 284
            $association->setValue($entity, $newValue);
2323
2324 284
            if ($association->getInversedBy()
2325 284
                && $association instanceof OneToOneAssociationMetadata
2326
                // @TODO refactor this
2327
                // we don't want to set any values in un-initialized proxies
2328
                && ! (
2329 56
                    $newValue instanceof GhostObjectInterface
2330 284
                    && ! $newValue->isProxyInitialized()
2331
                )
2332
            ) {
2333 19
                $inverseAssociation = $targetClass->getProperty($association->getInversedBy());
2334
2335 284
                $inverseAssociation->setValue($newValue, $entity);
2336
            }
2337
        }
2338
2339
        // defer invoking of postLoad event to hydration complete step
2340 661
        $this->hydrationCompleteHandler->deferPostLoadInvoking($class, $entity);
2341
2342 661
        return $entity;
2343
    }
2344
2345 861
    public function triggerEagerLoads()
2346
    {
2347 861
        if (! $this->eagerLoadingEntities) {
2348 861
            return;
2349
        }
2350
2351
        // avoid infinite recursion
2352 7
        $eagerLoadingEntities       = $this->eagerLoadingEntities;
2353 7
        $this->eagerLoadingEntities = [];
2354
2355 7
        foreach ($eagerLoadingEntities as $entityName => $ids) {
2356 7
            if (! $ids) {
2357
                continue;
2358
            }
2359
2360 7
            $class = $this->em->getClassMetadata($entityName);
2361
2362 7
            $this->getEntityPersister($entityName)->loadAll(
2363 7
                array_combine($class->identifier, [array_values($ids)])
2364
            );
2365
        }
2366 7
    }
2367
2368
    /**
2369
     * Initializes (loads) an uninitialized persistent collection of an entity.
2370
     *
2371
     * @param PersistentCollection $collection The collection to initialize.
2372
     *
2373
     * @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733.
2374
     */
2375 139
    public function loadCollection(PersistentCollection $collection)
2376
    {
2377 139
        $association = $collection->getMapping();
2378 139
        $persister   = $this->getEntityPersister($association->getTargetEntity());
2379
2380 139
        if ($association instanceof OneToManyAssociationMetadata) {
2381 74
            $persister->loadOneToManyCollection($association, $collection->getOwner(), $collection);
2382
        } else {
2383 75
            $persister->loadManyToManyCollection($association, $collection->getOwner(), $collection);
2384
        }
2385
2386 139
        $collection->setInitialized(true);
2387 139
    }
2388
2389
    /**
2390
     * Gets the identity map of the UnitOfWork.
2391
     *
2392
     * @return object[]
2393
     */
2394 1
    public function getIdentityMap()
2395
    {
2396 1
        return $this->identityMap;
2397
    }
2398
2399
    /**
2400
     * Gets the original data of an entity. The original data is the data that was
2401
     * present at the time the entity was reconstituted from the database.
2402
     *
2403
     * @param object $entity
2404
     *
2405
     * @return mixed[]
2406
     */
2407 121
    public function getOriginalEntityData($entity)
2408
    {
2409 121
        $oid = spl_object_id($entity);
2410
2411 121
        return $this->originalEntityData[$oid] ?? [];
2412
    }
2413
2414
    /**
2415
     * @param object  $entity
2416
     * @param mixed[] $data
2417
     *
2418
     * @ignore
2419
     */
2420
    public function setOriginalEntityData($entity, array $data)
2421
    {
2422
        $this->originalEntityData[spl_object_id($entity)] = $data;
2423
    }
2424
2425
    /**
2426
     * INTERNAL:
2427
     * Sets a property value of the original data array of an entity.
2428
     *
2429
     * @param string $oid
2430
     * @param string $property
2431
     * @param mixed  $value
2432
     *
2433
     * @ignore
2434
     */
2435 301
    public function setOriginalEntityProperty($oid, $property, $value)
2436
    {
2437 301
        $this->originalEntityData[$oid][$property] = $value;
2438 301
    }
2439
2440
    /**
2441
     * Gets the identifier of an entity.
2442
     * The returned value is always an array of identifier values. If the entity
2443
     * has a composite identifier then the identifier values are in the same
2444
     * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
2445
     *
2446
     * @param object $entity
2447
     *
2448
     * @return mixed[] The identifier values.
2449
     */
2450 568
    public function getEntityIdentifier($entity)
2451
    {
2452 568
        return $this->entityIdentifiers[spl_object_id($entity)];
2453
    }
2454
2455
    /**
2456
     * Processes an entity instance to extract their identifier values.
2457
     *
2458
     * @param object $entity The entity instance.
2459
     *
2460
     * @return mixed A scalar value.
2461
     *
2462
     * @throws ORMInvalidArgumentException
2463
     */
2464 70
    public function getSingleIdentifierValue($entity)
2465
    {
2466 70
        $class     = $this->em->getClassMetadata(get_class($entity));
2467 70
        $persister = $this->getEntityPersister($class->getClassName());
2468
2469 70
        if ($class->isIdentifierComposite()) {
2470
            throw ORMInvalidArgumentException::invalidCompositeIdentifier();
2471
        }
2472
2473 70
        $values = $this->isInIdentityMap($entity)
2474 58
            ? $this->getEntityIdentifier($entity)
2475 70
            : $persister->getIdentifier($entity);
2476
2477 70
        return $values[$class->identifier[0]] ?? null;
2478
    }
2479
2480
    /**
2481
     * Tries to find an entity with the given identifier in the identity map of
2482
     * this UnitOfWork.
2483
     *
2484
     * @param mixed|mixed[] $id            The entity identifier to look for.
2485
     * @param string        $rootClassName The name of the root class of the mapped entity hierarchy.
2486
     *
2487
     * @return object|bool Returns the entity with the specified identifier if it exists in
2488
     *                     this UnitOfWork, FALSE otherwise.
2489
     */
2490 538
    public function tryGetById($id, $rootClassName)
2491
    {
2492 538
        $idHash = implode(' ', (array) $id);
2493
2494 538
        return $this->identityMap[$rootClassName][$idHash] ?? false;
2495
    }
2496
2497
    /**
2498
     * Schedules an entity for dirty-checking at commit-time.
2499
     *
2500
     * @param object $entity The entity to schedule for dirty-checking.
2501
     */
2502 5
    public function scheduleForSynchronization($entity)
2503
    {
2504 5
        $rootClassName = $this->em->getClassMetadata(get_class($entity))->getRootClassName();
2505
2506 5
        $this->scheduledForSynchronization[$rootClassName][spl_object_id($entity)] = $entity;
2507 5
    }
2508
2509
    /**
2510
     * Checks whether the UnitOfWork has any pending insertions.
2511
     *
2512
     * @return bool TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
2513
     */
2514
    public function hasPendingInsertions()
2515
    {
2516
        return ! empty($this->entityInsertions);
2517
    }
2518
2519
    /**
2520
     * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
2521
     * number of entities in the identity map.
2522
     *
2523
     * @return int
2524
     */
2525 1
    public function size()
2526
    {
2527 1
        return array_sum(array_map('count', $this->identityMap));
2528
    }
2529
2530
    /**
2531
     * Gets the EntityPersister for an Entity.
2532
     *
2533
     * @param string $entityName The name of the Entity.
2534
     *
2535
     * @return EntityPersister
2536
     */
2537 1085
    public function getEntityPersister($entityName)
2538
    {
2539 1085
        if (isset($this->entityPersisters[$entityName])) {
2540 1031
            return $this->entityPersisters[$entityName];
2541
        }
2542
2543 1085
        $class = $this->em->getClassMetadata($entityName);
2544
2545
        switch (true) {
2546 1085
            case $class->inheritanceType === InheritanceType::NONE:
2547 1042
                $persister = new BasicEntityPersister($this->em, $class);
2548 1042
                break;
2549
2550 385
            case $class->inheritanceType === InheritanceType::SINGLE_TABLE:
2551 223
                $persister = new SingleTablePersister($this->em, $class);
2552 223
                break;
2553
2554 355
            case $class->inheritanceType === InheritanceType::JOINED:
2555 355
                $persister = new JoinedSubclassPersister($this->em, $class);
2556 355
                break;
2557
2558
            default:
2559
                throw new RuntimeException('No persister found for entity.');
2560
        }
2561
2562 1085
        if ($this->hasCache && $class->getCache()) {
2563 131
            $persister = $this->em->getConfiguration()
2564 131
                ->getSecondLevelCacheConfiguration()
2565 131
                ->getCacheFactory()
2566 131
                ->buildCachedEntityPersister($this->em, $persister, $class);
2567
        }
2568
2569 1085
        $this->entityPersisters[$entityName] = $persister;
2570
2571 1085
        return $this->entityPersisters[$entityName];
2572
    }
2573
2574
    /**
2575
     * Gets a collection persister for a collection-valued association.
2576
     *
2577
     * @return CollectionPersister
2578
     */
2579 565
    public function getCollectionPersister(ToManyAssociationMetadata $association)
2580
    {
2581 565
        $role = $association->getCache()
2582 78
            ? sprintf('%s::%s', $association->getSourceEntity(), $association->getName())
2583 565
            : get_class($association);
2584
2585 565
        if (isset($this->collectionPersisters[$role])) {
2586 431
            return $this->collectionPersisters[$role];
2587
        }
2588
2589 565
        $persister = $association instanceof OneToManyAssociationMetadata
2590 402
            ? new OneToManyPersister($this->em)
2591 565
            : new ManyToManyPersister($this->em);
2592
2593 565
        if ($this->hasCache && $association->getCache()) {
2594 77
            $persister = $this->em->getConfiguration()
2595 77
                ->getSecondLevelCacheConfiguration()
2596 77
                ->getCacheFactory()
2597 77
                ->buildCachedCollectionPersister($this->em, $persister, $association);
2598
        }
2599
2600 565
        $this->collectionPersisters[$role] = $persister;
2601
2602 565
        return $this->collectionPersisters[$role];
2603
    }
2604
2605
    /**
2606
     * INTERNAL:
2607
     * Registers an entity as managed.
2608
     *
2609
     * @param object  $entity The entity.
2610
     * @param mixed[] $id     Map containing identifier field names as key and its associated values.
2611
     * @param mixed[] $data   The original entity data.
2612
     */
2613 291
    public function registerManaged($entity, array $id, array $data)
2614
    {
2615 291
        $isProxy = $entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized();
2616 291
        $oid     = spl_object_id($entity);
2617
2618 291
        $this->entityIdentifiers[$oid]  = $id;
2619 291
        $this->entityStates[$oid]       = self::STATE_MANAGED;
2620 291
        $this->originalEntityData[$oid] = $data;
2621
2622 291
        $this->addToIdentityMap($entity);
2623
2624 285
        if ($entity instanceof NotifyPropertyChanged && ! $isProxy) {
2625 1
            $entity->addPropertyChangedListener($this);
2626
        }
2627 285
    }
2628
2629
    /**
2630
     * INTERNAL:
2631
     * Clears the property changeset of the entity with the given OID.
2632
     *
2633
     * @param string $oid The entity's OID.
2634
     */
2635
    public function clearEntityChangeSet($oid)
2636
    {
2637
        unset($this->entityChangeSets[$oid]);
2638
    }
2639
2640
    /* PropertyChangedListener implementation */
2641
2642
    /**
2643
     * Notifies this UnitOfWork of a property change in an entity.
2644
     *
2645
     * @param object $entity       The entity that owns the property.
2646
     * @param string $propertyName The name of the property that changed.
2647
     * @param mixed  $oldValue     The old value of the property.
2648
     * @param mixed  $newValue     The new value of the property.
2649
     */
2650 3
    public function propertyChanged($entity, $propertyName, $oldValue, $newValue)
2651
    {
2652 3
        $class = $this->em->getClassMetadata(get_class($entity));
2653
2654 3
        if (! $class->getProperty($propertyName)) {
2655
            return; // ignore non-persistent fields
2656
        }
2657
2658 3
        $oid = spl_object_id($entity);
2659
2660
        // Update changeset and mark entity for synchronization
2661 3
        $this->entityChangeSets[$oid][$propertyName] = [$oldValue, $newValue];
2662
2663 3
        if (! isset($this->scheduledForSynchronization[$class->getRootClassName()][$oid])) {
2664 3
            $this->scheduleForSynchronization($entity);
2665
        }
2666 3
    }
2667
2668
    /**
2669
     * Gets the currently scheduled entity insertions in this UnitOfWork.
2670
     *
2671
     * @return object[]
2672
     */
2673 2
    public function getScheduledEntityInsertions()
2674
    {
2675 2
        return $this->entityInsertions;
2676
    }
2677
2678
    /**
2679
     * Gets the currently scheduled entity updates in this UnitOfWork.
2680
     *
2681
     * @return object[]
2682
     */
2683 3
    public function getScheduledEntityUpdates()
2684
    {
2685 3
        return $this->entityUpdates;
2686
    }
2687
2688
    /**
2689
     * Gets the currently scheduled entity deletions in this UnitOfWork.
2690
     *
2691
     * @return object[]
2692
     */
2693 1
    public function getScheduledEntityDeletions()
2694
    {
2695 1
        return $this->entityDeletions;
2696
    }
2697
2698
    /**
2699
     * Gets the currently scheduled complete collection deletions
2700
     *
2701
     * @return Collection[]|object[][]
2702
     */
2703 1
    public function getScheduledCollectionDeletions()
2704
    {
2705 1
        return $this->collectionDeletions;
2706
    }
2707
2708
    /**
2709
     * Gets the currently scheduled collection inserts, updates and deletes.
2710
     *
2711
     * @return Collection[]|object[][]
2712
     */
2713
    public function getScheduledCollectionUpdates()
2714
    {
2715
        return $this->collectionUpdates;
2716
    }
2717
2718
    /**
2719
     * Helper method to initialize a lazy loading proxy or persistent collection.
2720
     *
2721
     * @param object $obj
2722
     */
2723 2
    public function initializeObject($obj)
2724
    {
2725 2
        if ($obj instanceof GhostObjectInterface) {
2726 1
            $obj->initializeProxy();
2727
2728 1
            return;
2729
        }
2730
2731 1
        if ($obj instanceof PersistentCollection) {
2732 1
            $obj->initialize();
2733
        }
2734 1
    }
2735
2736
    /**
2737
     * Helper method to show an object as string.
2738
     *
2739
     * @param object $obj
2740
     *
2741
     * @return string
2742
     */
2743
    private static function objToStr($obj)
2744
    {
2745
        return method_exists($obj, '__toString') ? (string) $obj : get_class($obj) . '@' . spl_object_id($obj);
2746
    }
2747
2748
    /**
2749
     * Marks an entity as read-only so that it will not be considered for updates during UnitOfWork#commit().
2750
     *
2751
     * This operation cannot be undone as some parts of the UnitOfWork now keep gathering information
2752
     * on this object that might be necessary to perform a correct update.
2753
     *
2754
     * @param object $object
2755
     *
2756
     * @throws ORMInvalidArgumentException
2757
     */
2758 6
    public function markReadOnly($object)
2759
    {
2760 6
        if (! is_object($object) || ! $this->isInIdentityMap($object)) {
2761 1
            throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
2762
        }
2763
2764 5
        $this->readOnlyObjects[spl_object_id($object)] = true;
2765 5
    }
2766
2767
    /**
2768
     * Is this entity read only?
2769
     *
2770
     * @param object $object
2771
     *
2772
     * @return bool
2773
     *
2774
     * @throws ORMInvalidArgumentException
2775
     */
2776 3
    public function isReadOnly($object)
2777
    {
2778 3
        if (! is_object($object)) {
2779
            throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
2780
        }
2781
2782 3
        return isset($this->readOnlyObjects[spl_object_id($object)]);
2783
    }
2784
2785
    /**
2786
     * Perform whatever processing is encapsulated here after completion of the transaction.
2787
     */
2788 1004
    private function afterTransactionComplete()
2789
    {
2790
        $this->performCallbackOnCachedPersister(static function (CachedPersister $persister) {
2791 95
            $persister->afterTransactionComplete();
2792 1004
        });
2793 1004
    }
2794
2795
    /**
2796
     * Perform whatever processing is encapsulated here after completion of the rolled-back.
2797
     */
2798 10
    private function afterTransactionRolledBack()
2799
    {
2800
        $this->performCallbackOnCachedPersister(static function (CachedPersister $persister) {
2801
            $persister->afterTransactionRolledBack();
2802 10
        });
2803 10
    }
2804
2805
    /**
2806
     * Performs an action after the transaction.
2807
     */
2808 1009
    private function performCallbackOnCachedPersister(callable $callback)
2809
    {
2810 1009
        if (! $this->hasCache) {
2811 914
            return;
2812
        }
2813
2814 95
        foreach (array_merge($this->entityPersisters, $this->collectionPersisters) as $persister) {
2815 95
            if ($persister instanceof CachedPersister) {
2816 95
                $callback($persister);
2817
            }
2818
        }
2819 95
    }
2820
2821 1014
    private function dispatchOnFlushEvent()
2822
    {
2823 1014
        if ($this->eventManager->hasListeners(Events::onFlush)) {
2824 4
            $this->eventManager->dispatchEvent(Events::onFlush, new OnFlushEventArgs($this->em));
2825
        }
2826 1014
    }
2827
2828 1009
    private function dispatchPostFlushEvent()
2829
    {
2830 1009
        if ($this->eventManager->hasListeners(Events::postFlush)) {
2831 5
            $this->eventManager->dispatchEvent(Events::postFlush, new PostFlushEventArgs($this->em));
2832
        }
2833 1008
    }
2834
2835
    /**
2836
     * Verifies if two given entities actually are the same based on identifier comparison
2837
     *
2838
     * @param object $entity1
2839
     * @param object $entity2
2840
     *
2841
     * @return bool
2842
     */
2843 17
    private function isIdentifierEquals($entity1, $entity2)
2844
    {
2845 17
        if ($entity1 === $entity2) {
2846
            return true;
2847
        }
2848
2849 17
        $class     = $this->em->getClassMetadata(get_class($entity1));
2850 17
        $persister = $this->getEntityPersister($class->getClassName());
2851
2852 17
        if ($class !== $this->em->getClassMetadata(get_class($entity2))) {
2853 11
            return false;
2854
        }
2855
2856 6
        $identifierFlattener = $this->em->getIdentifierFlattener();
2857
2858 6
        $oid1 = spl_object_id($entity1);
2859 6
        $oid2 = spl_object_id($entity2);
2860
2861 6
        $id1 = $this->entityIdentifiers[$oid1]
2862 6
            ?? $identifierFlattener->flattenIdentifier($class, $persister->getIdentifier($entity1));
2863 6
        $id2 = $this->entityIdentifiers[$oid2]
2864 6
            ?? $identifierFlattener->flattenIdentifier($class, $persister->getIdentifier($entity2));
2865
2866 6
        return $id1 === $id2 || implode(' ', $id1) === implode(' ', $id2);
2867
    }
2868
2869
    /**
2870
     * @throws ORMInvalidArgumentException
2871
     */
2872 1011
    private function assertThatThereAreNoUnintentionallyNonPersistedAssociations() : void
2873
    {
2874 1011
        $entitiesNeedingCascadePersist = array_diff_key($this->nonCascadedNewDetectedEntities, $this->entityInsertions);
2875
2876 1011
        $this->nonCascadedNewDetectedEntities = [];
2877
2878 1011
        if ($entitiesNeedingCascadePersist) {
2879 4
            throw ORMInvalidArgumentException::newEntitiesFoundThroughRelationships(
2880 4
                array_values($entitiesNeedingCascadePersist)
2881
            );
2882
        }
2883 1009
    }
2884
2885
    /**
2886
     * This method called by hydrators, and indicates that hydrator totally completed current hydration cycle.
2887
     * Unit of work able to fire deferred events, related to loading events here.
2888
     *
2889
     * @internal should be called internally from object hydrators
2890
     */
2891 877
    public function hydrationComplete()
2892
    {
2893 877
        $this->hydrationCompleteHandler->hydrationComplete();
2894 877
    }
2895
}
2896