Completed
Push — master ( e8eaf8...d8f671 )
by Marco
24s queued 17s
created

UnitOfWork::postCommitCleanup()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 10
nc 1
nop 0
dl 0
loc 12
ccs 11
cts 11
cp 1
crap 1
rs 9.9332
c 0
b 0
f 0
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 2274
    public function __construct(EntityManagerInterface $em)
309
    {
310 2274
        $this->em                       = $em;
311 2274
        $this->eventManager             = $em->getEventManager();
312 2274
        $this->listenersInvoker         = new ListenersInvoker($em);
313 2274
        $this->hasCache                 = $em->getConfiguration()->isSecondLevelCacheEnabled();
314 2274
        $this->instantiator             = new Instantiator();
315 2274
        $this->hydrationCompleteHandler = new HydrationCompleteHandler($this->listenersInvoker, $em);
316 2274
        $this->normalizeIdentifier      = new NormalizeIdentifier();
317 2274
    }
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 1020
    public function commit()
335
    {
336
        // Raise preFlush
337 1020
        if ($this->eventManager->hasListeners(Events::preFlush)) {
338 2
            $this->eventManager->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em));
339
        }
340
341 1020
        $this->computeChangeSets();
342
343 1018
        if (! ($this->entityInsertions ||
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityInsertions of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
344 158
                $this->entityDeletions ||
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityDeletions of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
345 123
                $this->entityUpdates ||
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityUpdates of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
346 37
                $this->collectionUpdates ||
347 34
                $this->collectionDeletions ||
348 1018
                $this->orphanRemovals)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->orphanRemovals of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
349 22
            $this->dispatchOnFlushEvent();
350 22
            $this->dispatchPostFlushEvent();
351
352 22
            $this->postCommitCleanup();
353
354 22
            return; // Nothing to do.
355
        }
356
357 1013
        $this->assertThatThereAreNoUnintentionallyNonPersistedAssociations();
358
359 1011
        if ($this->orphanRemovals) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->orphanRemovals of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
360 15
            foreach ($this->orphanRemovals as $orphan) {
361 15
                $this->remove($orphan);
362
            }
363
        }
364
365 1011
        $this->dispatchOnFlushEvent();
366
367
        // Now we need a commit order to maintain referential integrity
368 1011
        $commitOrder = $this->getCommitOrder();
369
370 1011
        $conn = $this->em->getConnection();
371 1011
        $conn->beginTransaction();
372
373
        try {
374
            // Collection deletions (deletions of complete collections)
375 1011
            foreach ($this->collectionDeletions as $collectionToDelete) {
376 19
                $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
377
            }
378
379 1011
            if ($this->entityInsertions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityInsertions of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
380 1007
                foreach ($commitOrder as $class) {
381 1007
                    $this->executeInserts($class);
382
                }
383
            }
384
385 1010
            if ($this->entityUpdates) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityUpdates of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
386 111
                foreach ($commitOrder as $class) {
387 111
                    $this->executeUpdates($class);
388
                }
389
            }
390
391
            // Extra updates that were requested by persisters.
392 1006
            if ($this->extraUpdates) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->extraUpdates of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
393 29
                $this->executeExtraUpdates();
394
            }
395
396
            // Collection updates (deleteRows, updateRows, insertRows)
397 1006
            foreach ($this->collectionUpdates as $collectionToUpdate) {
398 526
                $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
399
            }
400
401
            // Entity deletions come last and need to be in reverse commit order
402 1006
            if ($this->entityDeletions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityDeletions of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
403 60
                foreach (array_reverse($commitOrder) as $committedEntityName) {
404 60
                    if (! $this->entityDeletions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityDeletions of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
405 33
                        break; // just a performance optimisation
406
                    }
407
408 60
                    $this->executeDeletions($committedEntityName);
409
                }
410
            }
411
412 1006
            $conn->commit();
413 10
        } catch (Throwable $e) {
414 10
            $this->em->close();
415 10
            $conn->rollBack();
416
417 10
            $this->afterTransactionRolledBack();
418
419 10
            throw $e;
420
        }
421
422 1006
        $this->afterTransactionComplete();
423
424
        // Take new snapshots from visited collections
425 1006
        foreach ($this->visitedCollections as $coll) {
426 525
            $coll->takeSnapshot();
427
        }
428
429 1006
        $this->dispatchPostFlushEvent();
430
431 1005
        $this->postCommitCleanup();
432 1005
    }
433
434 1010
    private function postCommitCleanup() : void
435
    {
436 1010
        $this->entityInsertions            =
437 1010
        $this->entityUpdates               =
438 1010
        $this->entityDeletions             =
439 1010
        $this->extraUpdates                =
440 1010
        $this->entityChangeSets            =
441 1010
        $this->collectionUpdates           =
442 1010
        $this->collectionDeletions         =
443 1010
        $this->visitedCollections          =
444 1010
        $this->scheduledForSynchronization =
445 1010
        $this->orphanRemovals              = [];
446 1010
    }
447
448
    /**
449
     * Computes the changesets of all entities scheduled for insertion.
450
     */
451 1020
    private function computeScheduleInsertsChangeSets()
452
    {
453 1020
        foreach ($this->entityInsertions as $entity) {
454 1011
            $class = $this->em->getClassMetadata(get_class($entity));
455
456 1011
            $this->computeChangeSet($class, $entity);
457
        }
458 1018
    }
459
460
    /**
461
     * Executes any extra updates that have been scheduled.
462
     */
463 29
    private function executeExtraUpdates()
464
    {
465 29
        foreach ($this->extraUpdates as $oid => $update) {
466 29
            [$entity, $changeset] = $update;
467
468 29
            $this->entityChangeSets[$oid] = $changeset;
469
470 29
            $this->getEntityPersister(get_class($entity))->update($entity);
471
        }
472
473 29
        $this->extraUpdates = [];
474 29
    }
475
476
    /**
477
     * Gets the changeset for an entity.
478
     *
479
     * @param object $entity
480
     *
481
     * @return mixed[]
482
     */
483
    public function & getEntityChangeSet($entity)
484
    {
485 1006
        $oid  = spl_object_id($entity);
486 1006
        $data = [];
487
488 1006
        if (! isset($this->entityChangeSets[$oid])) {
489 2
            return $data;
490
        }
491
492 1006
        return $this->entityChangeSets[$oid];
493
    }
494
495
    /**
496
     * Computes the changes that happened to a single entity.
497
     *
498
     * Modifies/populates the following properties:
499
     *
500
     * {@link originalEntityData}
501
     * If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
502
     * then it was not fetched from the database and therefore we have no original
503
     * entity data yet. All of the current entity data is stored as the original entity data.
504
     *
505
     * {@link entityChangeSets}
506
     * The changes detected on all properties of the entity are stored there.
507
     * A change is a tuple array where the first entry is the old value and the second
508
     * entry is the new value of the property. Changesets are used by persisters
509
     * to INSERT/UPDATE the persistent entity state.
510
     *
511
     * {@link entityUpdates}
512
     * If the entity is already fully MANAGED (has been fetched from the database before)
513
     * and any changes to its properties are detected, then a reference to the entity is stored
514
     * there to mark it for an update.
515
     *
516
     * {@link collectionDeletions}
517
     * If a PersistentCollection has been de-referenced in a fully MANAGED entity,
518
     * then this collection is marked for deletion.
519
     *
520
     * @internal Don't call from the outside.
521
     *
522
     * @param ClassMetadata $class  The class descriptor of the entity.
523
     * @param object        $entity The entity for which to compute the changes.
524
     *
525
     * @ignore
526
     */
527 1021
    public function computeChangeSet(ClassMetadata $class, $entity)
528
    {
529 1021
        $oid = spl_object_id($entity);
530
531 1021
        if (isset($this->readOnlyObjects[$oid])) {
532 2
            return;
533
        }
534
535 1021
        if ($class->inheritanceType !== InheritanceType::NONE) {
536 333
            $class = $this->em->getClassMetadata(get_class($entity));
537
        }
538
539 1021
        $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preFlush) & ~ListenersInvoker::INVOKE_MANAGER;
540
541 1021
        if ($invoke !== ListenersInvoker::INVOKE_NONE) {
542 130
            $this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke);
543
        }
544
545 1021
        $actualData = [];
546
547 1021
        foreach ($class->getDeclaredPropertiesIterator() as $name => $property) {
0 ignored issues
show
Bug introduced by
The method getDeclaredPropertiesIterator() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

547
        foreach ($class->/** @scrutinizer ignore-call */ getDeclaredPropertiesIterator() as $name => $property) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
548 1021
            $value = $property->getValue($entity);
549
550 1021
            if ($property instanceof ToManyAssociationMetadata && $value !== null) {
551 773
                if ($value instanceof PersistentCollection && $value->getOwner() === $entity) {
552 186
                    continue;
553
                }
554
555 770
                $value = $property->wrap($entity, $value, $this->em);
556
557 770
                $property->setValue($entity, $value);
558
559 770
                $actualData[$name] = $value;
560
561 770
                continue;
562
            }
563
564 1021
            if (( ! $class->isIdentifier($name)
565 1021
                    || ! $class->getProperty($name) instanceof FieldMetadata
0 ignored issues
show
Bug introduced by
The method getProperty() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

565
                    || ! $class->/** @scrutinizer ignore-call */ getProperty($name) instanceof FieldMetadata

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
566 1021
                    || ! $class->getProperty($name)->hasValueGenerator()
0 ignored issues
show
Bug introduced by
The method hasValueGenerator() does not exist on Doctrine\ORM\Mapping\Property. It seems like you code against a sub-type of Doctrine\ORM\Mapping\Property such as Doctrine\ORM\Mapping\FieldMetadata. ( Ignorable by Annotation )

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

566
                    || ! $class->getProperty($name)->/** @scrutinizer ignore-call */ hasValueGenerator()
Loading history...
567 1021
                    || $class->getProperty($name)->getValueGenerator()->getType() !== GeneratorType::IDENTITY
0 ignored issues
show
Bug introduced by
The method getValueGenerator() does not exist on Doctrine\ORM\Mapping\Property. Did you maybe mean getValue()? ( Ignorable by Annotation )

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

567
                    || $class->getProperty($name)->/** @scrutinizer ignore-call */ getValueGenerator()->getType() !== GeneratorType::IDENTITY

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
568 1021
                ) && (! $class->isVersioned() || $name !== $class->versionProperty->getName())) {
0 ignored issues
show
Bug introduced by
The method isVersioned() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

568
                ) && (! $class->/** @scrutinizer ignore-call */ isVersioned() || $name !== $class->versionProperty->getName())) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
569 988
                $actualData[$name] = $value;
570
            }
571
        }
572
573 1021
        if (! isset($this->originalEntityData[$oid])) {
574
            // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
575
            // These result in an INSERT.
576 1017
            $this->originalEntityData[$oid] = $actualData;
577 1017
            $changeSet                      = [];
578
579 1017
            foreach ($actualData as $propName => $actualValue) {
580 995
                $property = $class->getProperty($propName);
581
582 995
                if (($property instanceof FieldMetadata) ||
583 995
                    ($property instanceof ToOneAssociationMetadata && $property->isOwningSide())) {
584 980
                    $changeSet[$propName] = [null, $actualValue];
585
                }
586
            }
587
588 1017
            $this->entityChangeSets[$oid] = $changeSet;
589
        } else {
590
            // Entity is "fully" MANAGED: it was already fully persisted before
591
            // and we have a copy of the original data
592 257
            $originalData           = $this->originalEntityData[$oid];
593 257
            $isChangeTrackingNotify = $class->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY;
594 257
            $changeSet              = $isChangeTrackingNotify && isset($this->entityChangeSets[$oid])
595
                ? $this->entityChangeSets[$oid]
596 257
                : [];
597
598 257
            foreach ($actualData as $propName => $actualValue) {
599
                // skip field, its a partially omitted one!
600 245
                if (! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
601 40
                    continue;
602
                }
603
604 245
                $orgValue = $originalData[$propName];
605
606
                // skip if value haven't changed
607 245
                if ($orgValue === $actualValue) {
608 228
                    continue;
609
                }
610
611 109
                $property = $class->getProperty($propName);
612
613
                // Persistent collection was exchanged with the "originally"
614
                // created one. This can only mean it was cloned and replaced
615
                // on another entity.
616 109
                if ($actualValue instanceof PersistentCollection) {
617 8
                    $owner = $actualValue->getOwner();
618
619 8
                    if ($owner === null) { // cloned
620
                        $actualValue->setOwner($entity, $property);
0 ignored issues
show
Bug introduced by
It seems like $property can also be of type null; however, parameter $association of Doctrine\ORM\PersistentCollection::setOwner() does only seem to accept Doctrine\ORM\Mapping\ToManyAssociationMetadata, 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

620
                        $actualValue->setOwner($entity, /** @scrutinizer ignore-type */ $property);
Loading history...
621 8
                    } elseif ($owner !== $entity) { // no clone, we have to fix
622
                        if (! $actualValue->isInitialized()) {
623
                            $actualValue->initialize(); // we have to do this otherwise the cols share state
624
                        }
625
626
                        $newValue = clone $actualValue;
627
628
                        $newValue->setOwner($entity, $property);
629
630
                        $property->setValue($entity, $newValue);
631
                    }
632
                }
633
634
                switch (true) {
635 109
                    case $property instanceof FieldMetadata:
636 58
                        if ($isChangeTrackingNotify) {
637
                            // Continue inside switch behaves as break.
638
                            // We are required to use continue 2, since we need to continue to next $actualData item
639
                            continue 2;
640
                        }
641
642 58
                        $changeSet[$propName] = [$orgValue, $actualValue];
643 58
                        break;
644
645 57
                    case $property instanceof ToOneAssociationMetadata:
646 46
                        if ($property->isOwningSide()) {
647 20
                            $changeSet[$propName] = [$orgValue, $actualValue];
648
                        }
649
650 46
                        if ($orgValue !== null && $property->isOrphanRemoval()) {
651 4
                            $this->scheduleOrphanRemoval($orgValue);
652
                        }
653
654 46
                        break;
655
656 12
                    case $property instanceof ToManyAssociationMetadata:
657
                        // Check if original value exists
658 9
                        if ($orgValue instanceof PersistentCollection) {
659
                            // A PersistentCollection was de-referenced, so delete it.
660 8
                            if (! $this->isCollectionScheduledForDeletion($orgValue)) {
661 8
                                $this->scheduleCollectionDeletion($orgValue);
662
663 8
                                $changeSet[$propName] = $orgValue; // Signal changeset, to-many associations will be ignored
664
                            }
665
                        }
666
667 9
                        break;
668
669
                    default:
670
                        // Do nothing
671
                }
672
            }
673
674 257
            if ($changeSet) {
675 84
                $this->entityChangeSets[$oid]   = $changeSet;
676 84
                $this->originalEntityData[$oid] = $actualData;
677 84
                $this->entityUpdates[$oid]      = $entity;
678
            }
679
        }
680
681
        // Look for changes in associations of the entity
682 1021
        foreach ($class->getDeclaredPropertiesIterator() as $property) {
683 1021
            if (! $property instanceof AssociationMetadata) {
684 1021
                continue;
685
            }
686
687 886
            $value = $property->getValue($entity);
688
689 886
            if ($value === null) {
690 625
                continue;
691
            }
692
693 862
            $this->computeAssociationChanges($property, $value);
694
695 854
            if ($property instanceof ManyToManyAssociationMetadata &&
696 854
                $value instanceof PersistentCollection &&
697 854
                ! isset($this->entityChangeSets[$oid]) &&
698 854
                $property->isOwningSide() &&
699 854
                $value->isDirty()) {
700 31
                $this->entityChangeSets[$oid]   = [];
701 31
                $this->originalEntityData[$oid] = $actualData;
702 31
                $this->entityUpdates[$oid]      = $entity;
703
            }
704
        }
705 1013
    }
706
707
    /**
708
     * Computes all the changes that have been done to entities and collections
709
     * since the last commit and stores these changes in the _entityChangeSet map
710
     * temporarily for access by the persisters, until the UoW commit is finished.
711
     */
712 1020
    public function computeChangeSets()
713
    {
714
        // Compute changes for INSERTed entities first. This must always happen.
715 1020
        $this->computeScheduleInsertsChangeSets();
716
717
        // Compute changes for other MANAGED entities. Change tracking policies take effect here.
718 1018
        foreach ($this->identityMap as $className => $entities) {
719 446
            $class = $this->em->getClassMetadata($className);
720
721
            // Skip class if instances are read-only
722 446
            if ($class->isReadOnly()) {
0 ignored issues
show
Bug introduced by
The method isReadOnly() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

722
            if ($class->/** @scrutinizer ignore-call */ isReadOnly()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
723 1
                continue;
724
            }
725
726
            // If change tracking is explicit or happens through notification, then only compute
727
            // changes on entities of that type that are explicitly marked for synchronization.
728
            switch (true) {
729 445
                case $class->changeTrackingPolicy === ChangeTrackingPolicy::DEFERRED_IMPLICIT:
0 ignored issues
show
Bug introduced by
Accessing changeTrackingPolicy on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
730 442
                    $entitiesToProcess = $entities;
731 442
                    break;
732
733 4
                case isset($this->scheduledForSynchronization[$className]):
734 4
                    $entitiesToProcess = $this->scheduledForSynchronization[$className];
735 4
                    break;
736
737
                default:
738 1
                    $entitiesToProcess = [];
739
            }
740
741 445
            foreach ($entitiesToProcess as $entity) {
742
                // Ignore uninitialized proxy objects
743 425
                if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
744 38
                    continue;
745
                }
746
747
                // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
748 423
                $oid = spl_object_id($entity);
749
750 423
                if (! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
751 257
                    $this->computeChangeSet($class, $entity);
752
                }
753
            }
754
        }
755 1018
    }
756
757
    /**
758
     * Computes the changes of an association.
759
     *
760
     * @param AssociationMetadata $association The association mapping.
761
     * @param mixed               $value       The value of the association.
762
     *
763
     * @throws ORMInvalidArgumentException
764
     * @throws ORMException
765
     */
766 862
    private function computeAssociationChanges(AssociationMetadata $association, $value)
767
    {
768 862
        if ($value instanceof GhostObjectInterface && ! $value->isProxyInitialized()) {
769 31
            return;
770
        }
771
772 861
        if ($value instanceof PersistentCollection && $value->isDirty()) {
773 529
            $coid = spl_object_id($value);
774
775 529
            $this->collectionUpdates[$coid]  = $value;
776 529
            $this->visitedCollections[$coid] = $value;
777
        }
778
779
        // Look through the entities, and in any of their associations,
780
        // for transient (new) entities, recursively. ("Persistence by reachability")
781
        // Unwrap. Uninitialized collections will simply be empty.
782 861
        $unwrappedValue = $association instanceof ToOneAssociationMetadata ? [$value] : $value->unwrap();
783 861
        $targetEntity   = $association->getTargetEntity();
784 861
        $targetClass    = $this->em->getClassMetadata($targetEntity);
785
786 861
        foreach ($unwrappedValue as $key => $entry) {
787 718
            if (! ($entry instanceof $targetEntity)) {
788 8
                throw ORMInvalidArgumentException::invalidAssociation($targetClass, $association, $entry);
789
            }
790
791 710
            $state = $this->getEntityState($entry, self::STATE_NEW);
792
793 710
            if (! ($entry instanceof $targetEntity)) {
794
                throw UnexpectedAssociationValue::create(
795
                    $association->getSourceEntity(),
796
                    $association->getName(),
797
                    get_class($entry),
798
                    $targetEntity
799
                );
800
            }
801
802
            switch ($state) {
803 710
                case self::STATE_NEW:
804 41
                    if (! in_array('persist', $association->getCascade(), true)) {
805 5
                        $this->nonCascadedNewDetectedEntities[spl_object_id($entry)] = [$association, $entry];
806
807 5
                        break;
808
                    }
809
810 37
                    $this->persistNew($targetClass, $entry);
811 37
                    $this->computeChangeSet($targetClass, $entry);
812
813 37
                    break;
814
815 703
                case self::STATE_REMOVED:
816
                    // Consume the $value as array (it's either an array or an ArrayAccess)
817
                    // and remove the element from Collection.
818 4
                    if ($association instanceof ToManyAssociationMetadata) {
819 3
                        unset($value[$key]);
820
                    }
821 4
                    break;
822
823 703
                case self::STATE_DETACHED:
824
                    // Can actually not happen right now as we assume STATE_NEW,
825
                    // so the exception will be raised from the DBAL layer (constraint violation).
826
                    throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($association, $entry);
827
                    break;
828
829
                default:
830
                    // MANAGED associated entities are already taken into account
831
                    // during changeset calculation anyway, since they are in the identity map.
832
            }
833
        }
834 853
    }
835
836
    /**
837
     * @param ClassMetadata $class
838
     * @param object        $entity
839
     */
840 1032
    private function persistNew($class, $entity)
841
    {
842 1032
        $oid    = spl_object_id($entity);
843 1032
        $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::prePersist);
844
845 1032
        if ($invoke !== ListenersInvoker::INVOKE_NONE) {
846 132
            $this->listenersInvoker->invoke($class, Events::prePersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
847
        }
848
849 1032
        $generationPlan = $class->getValueGenerationPlan();
850 1032
        $persister      = $this->getEntityPersister($class->getClassName());
851 1032
        $generationPlan->executeImmediate($this->em, $entity);
852
853 1032
        if (! $generationPlan->containsDeferred()) {
854 221
            $id                            = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $persister->getIdentifier($entity));
855 221
            $this->entityIdentifiers[$oid] = $id;
856
        }
857
858 1032
        $this->entityStates[$oid] = self::STATE_MANAGED;
859
860 1032
        $this->scheduleForInsert($entity);
861 1032
    }
862
863
    /**
864
     * INTERNAL:
865
     * Computes the changeset of an individual entity, independently of the
866
     * computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
867
     *
868
     * The passed entity must be a managed entity. If the entity already has a change set
869
     * because this method is invoked during a commit cycle then the change sets are added.
870
     * whereby changes detected in this method prevail.
871
     *
872
     * @param ClassMetadata $class  The class descriptor of the entity.
873
     * @param object        $entity The entity for which to (re)calculate the change set.
874
     *
875
     * @throws ORMInvalidArgumentException If the passed entity is not MANAGED.
876
     * @throws RuntimeException
877
     *
878
     * @ignore
879
     */
880 15
    public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) : void
881
    {
882 15
        $oid = spl_object_id($entity);
883
884 15
        if (! isset($this->entityStates[$oid]) || $this->entityStates[$oid] !== self::STATE_MANAGED) {
885
            throw ORMInvalidArgumentException::entityNotManaged($entity);
886
        }
887
888
        // skip if change tracking is "NOTIFY"
889 15
        if ($class->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY) {
890
            return;
891
        }
892
893 15
        if ($class->inheritanceType !== InheritanceType::NONE) {
894 3
            $class = $this->em->getClassMetadata(get_class($entity));
895
        }
896
897 15
        $actualData = [];
898
899 15
        foreach ($class->getDeclaredPropertiesIterator() as $name => $property) {
900
            switch (true) {
901 15
                case $property instanceof VersionFieldMetadata:
902
                    // Ignore version field
903
                    break;
904
905 15
                case $property instanceof FieldMetadata:
906 15
                    if (! $property->isPrimaryKey()
907 15
                        || ! $property->getValueGenerator()
908 15
                        || $property->getValueGenerator()->getType() !== GeneratorType::IDENTITY) {
909 15
                        $actualData[$name] = $property->getValue($entity);
910
                    }
911
912 15
                    break;
913
914 11
                case $property instanceof ToOneAssociationMetadata:
915 9
                    $actualData[$name] = $property->getValue($entity);
916 9
                    break;
917
            }
918
        }
919
920 15
        if (! isset($this->originalEntityData[$oid])) {
921
            throw new RuntimeException('Cannot call recomputeSingleEntityChangeSet before computeChangeSet on an entity.');
922
        }
923
924 15
        $originalData = $this->originalEntityData[$oid];
925 15
        $changeSet    = [];
926
927 15
        foreach ($actualData as $propName => $actualValue) {
928 15
            $orgValue = $originalData[$propName] ?? null;
929
930 15
            if ($orgValue !== $actualValue) {
931 7
                $changeSet[$propName] = [$orgValue, $actualValue];
932
            }
933
        }
934
935 15
        if ($changeSet) {
936 7
            if (isset($this->entityChangeSets[$oid])) {
937 6
                $this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
938 1
            } elseif (! isset($this->entityInsertions[$oid])) {
939 1
                $this->entityChangeSets[$oid] = $changeSet;
940 1
                $this->entityUpdates[$oid]    = $entity;
941
            }
942 7
            $this->originalEntityData[$oid] = $actualData;
943
        }
944 15
    }
945
946
    /**
947
     * Executes all entity insertions for entities of the specified type.
948
     */
949 1007
    private function executeInserts(ClassMetadata $class) : void
950
    {
951 1007
        $className      = $class->getClassName();
952 1007
        $persister      = $this->getEntityPersister($className);
953 1007
        $invoke         = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist);
954 1007
        $generationPlan = $class->getValueGenerationPlan();
955
956 1007
        foreach ($this->entityInsertions as $oid => $entity) {
957 1007
            if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) {
0 ignored issues
show
Bug introduced by
The method getClassName() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

957
            if ($this->em->getClassMetadata(get_class($entity))->/** @scrutinizer ignore-call */ getClassName() !== $className) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
958 854
                continue;
959
            }
960
961 1007
            $persister->insert($entity);
962
963 1006
            if ($generationPlan->containsDeferred()) {
964
                // Entity has post-insert IDs
965 943
                $oid = spl_object_id($entity);
966 943
                $id  = $persister->getIdentifier($entity);
967
968 943
                $this->entityIdentifiers[$oid]  = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $id);
969 943
                $this->entityStates[$oid]       = self::STATE_MANAGED;
970 943
                $this->originalEntityData[$oid] = $id + $this->originalEntityData[$oid];
971
972 943
                $this->addToIdentityMap($entity);
973
            }
974
975 1006
            unset($this->entityInsertions[$oid]);
976
977 1006
            if ($invoke !== ListenersInvoker::INVOKE_NONE) {
978 128
                $eventArgs = new LifecycleEventArgs($entity, $this->em);
979
980 128
                $this->listenersInvoker->invoke($class, Events::postPersist, $entity, $eventArgs, $invoke);
981
            }
982
        }
983 1007
    }
984
985
    /**
986
     * Executes all entity updates for entities of the specified type.
987
     *
988
     * @param ClassMetadata $class
989
     */
990 111
    private function executeUpdates($class)
991
    {
992 111
        $className        = $class->getClassName();
993 111
        $persister        = $this->getEntityPersister($className);
994 111
        $preUpdateInvoke  = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate);
995 111
        $postUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate);
996
997 111
        foreach ($this->entityUpdates as $oid => $entity) {
998 111
            if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) {
999 71
                continue;
1000
            }
1001
1002 111
            if ($preUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
1003 12
                $this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->getEntityChangeSet($entity)), $preUpdateInvoke);
1004
1005 12
                $this->recomputeSingleEntityChangeSet($class, $entity);
1006
            }
1007
1008 111
            if (! empty($this->entityChangeSets[$oid])) {
1009 81
                $persister->update($entity);
1010
            }
1011
1012 107
            unset($this->entityUpdates[$oid]);
1013
1014 107
            if ($postUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
1015 10
                $this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke);
1016
            }
1017
        }
1018 107
    }
1019
1020
    /**
1021
     * Executes all entity deletions for entities of the specified type.
1022
     *
1023
     * @param ClassMetadata $class
1024
     */
1025 60
    private function executeDeletions($class)
1026
    {
1027 60
        $className = $class->getClassName();
1028 60
        $persister = $this->getEntityPersister($className);
1029 60
        $invoke    = $this->listenersInvoker->getSubscribedSystems($class, Events::postRemove);
1030
1031 60
        foreach ($this->entityDeletions as $oid => $entity) {
1032 60
            if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) {
1033 24
                continue;
1034
            }
1035
1036 60
            $persister->delete($entity);
1037
1038
            unset(
1039 60
                $this->entityDeletions[$oid],
1040 60
                $this->entityIdentifiers[$oid],
1041 60
                $this->originalEntityData[$oid],
1042 60
                $this->entityStates[$oid]
1043
            );
1044
1045
            // Entity with this $oid after deletion treated as NEW, even if the $oid
1046
            // is obtained by a new entity because the old one went out of scope.
1047 60
            if (! $class->isIdentifierComposite()) {
1048 57
                $property = $class->getProperty($class->getSingleIdentifierFieldName());
1049
1050 57
                if ($property instanceof FieldMetadata && $property->hasValueGenerator()) {
1051 50
                    $property->setValue($entity, null);
1052
                }
1053
            }
1054
1055 60
            if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1056 9
                $eventArgs = new LifecycleEventArgs($entity, $this->em);
1057
1058 9
                $this->listenersInvoker->invoke($class, Events::postRemove, $entity, $eventArgs, $invoke);
1059
            }
1060
        }
1061 59
    }
1062
1063
    /**
1064
     * Gets the commit order.
1065
     *
1066
     * @return ClassMetadata[]
1067
     */
1068 1011
    private function getCommitOrder()
1069
    {
1070 1011
        $calc = new Internal\CommitOrderCalculator();
1071
1072
        // See if there are any new classes in the changeset, that are not in the
1073
        // commit order graph yet (don't have a node).
1074
        // We have to inspect changeSet to be able to correctly build dependencies.
1075
        // It is not possible to use IdentityMap here because post inserted ids
1076
        // are not yet available.
1077 1011
        $newNodes = [];
1078
1079 1011
        foreach (array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions) as $entity) {
1080 1011
            $class = $this->em->getClassMetadata(get_class($entity));
1081
1082 1011
            if ($calc->hasNode($class->getClassName())) {
1083 635
                continue;
1084
            }
1085
1086 1011
            $calc->addNode($class->getClassName(), $class);
1087
1088 1011
            $newNodes[] = $class;
1089
        }
1090
1091
        // Calculate dependencies for new nodes
1092 1011
        while ($class = array_pop($newNodes)) {
1093 1011
            foreach ($class->getDeclaredPropertiesIterator() as $property) {
1094 1011
                if (! ($property instanceof ToOneAssociationMetadata && $property->isOwningSide())) {
1095 1011
                    continue;
1096
                }
1097
1098 834
                $targetClass = $this->em->getClassMetadata($property->getTargetEntity());
1099
1100 834
                if (! $calc->hasNode($targetClass->getClassName())) {
1101 637
                    $calc->addNode($targetClass->getClassName(), $targetClass);
1102
1103 637
                    $newNodes[] = $targetClass;
1104
                }
1105
1106 834
                $weight = ! array_filter(
1107 834
                    $property->getJoinColumns(),
1108
                    static function (JoinColumnMetadata $joinColumn) {
1109 834
                        return $joinColumn->isNullable();
1110 834
                    }
1111
                );
1112
1113 834
                $calc->addDependency($targetClass->getClassName(), $class->getClassName(), $weight);
0 ignored issues
show
Bug introduced by
$weight of type boolean is incompatible with the type integer expected by parameter $weight of Doctrine\ORM\Internal\Co...ulator::addDependency(). ( Ignorable by Annotation )

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

1113
                $calc->addDependency($targetClass->getClassName(), $class->getClassName(), /** @scrutinizer ignore-type */ $weight);
Loading history...
1114
1115
                // If the target class has mapped subclasses, these share the same dependency.
1116 834
                if (! $targetClass->getSubClasses()) {
0 ignored issues
show
Bug introduced by
The method getSubClasses() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

1116
                if (! $targetClass->/** @scrutinizer ignore-call */ getSubClasses()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1117 829
                    continue;
1118
                }
1119
1120 225
                foreach ($targetClass->getSubClasses() as $subClassName) {
1121 225
                    $targetSubClass = $this->em->getClassMetadata($subClassName);
1122
1123 225
                    if (! $calc->hasNode($subClassName)) {
1124 199
                        $calc->addNode($targetSubClass->getClassName(), $targetSubClass);
1125
1126 199
                        $newNodes[] = $targetSubClass;
1127
                    }
1128
1129 225
                    $calc->addDependency($targetSubClass->getClassName(), $class->getClassName(), 1);
1130
                }
1131
            }
1132
        }
1133
1134 1011
        return $calc->sort();
1135
    }
1136
1137
    /**
1138
     * Schedules an entity for insertion into the database.
1139
     * If the entity already has an identifier, it will be added to the identity map.
1140
     *
1141
     * @param object $entity The entity to schedule for insertion.
1142
     *
1143
     * @throws ORMInvalidArgumentException
1144
     * @throws InvalidArgumentException
1145
     */
1146 1033
    public function scheduleForInsert($entity)
1147
    {
1148 1033
        $oid = spl_object_id($entity);
1149
1150 1033
        if (isset($this->entityUpdates[$oid])) {
1151
            throw new InvalidArgumentException('Dirty entity can not be scheduled for insertion.');
1152
        }
1153
1154 1033
        if (isset($this->entityDeletions[$oid])) {
1155 1
            throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
1156
        }
1157 1033
        if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
1158 1
            throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
1159
        }
1160
1161 1033
        if (isset($this->entityInsertions[$oid])) {
1162 1
            throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
1163
        }
1164
1165 1033
        $this->entityInsertions[$oid] = $entity;
1166
1167 1033
        if (isset($this->entityIdentifiers[$oid])) {
1168 221
            $this->addToIdentityMap($entity);
1169
        }
1170
1171 1033
        if ($entity instanceof NotifyPropertyChanged) {
1172 5
            $entity->addPropertyChangedListener($this);
1173
        }
1174 1033
    }
1175
1176
    /**
1177
     * Checks whether an entity is scheduled for insertion.
1178
     *
1179
     * @param object $entity
1180
     *
1181
     * @return bool
1182
     */
1183 621
    public function isScheduledForInsert($entity)
1184
    {
1185 621
        return isset($this->entityInsertions[spl_object_id($entity)]);
1186
    }
1187
1188
    /**
1189
     * Schedules an entity for being updated.
1190
     *
1191
     * @param object $entity The entity to schedule for being updated.
1192
     *
1193
     * @throws ORMInvalidArgumentException
1194
     */
1195 1
    public function scheduleForUpdate($entity) : void
1196
    {
1197 1
        $oid = spl_object_id($entity);
1198
1199 1
        if (! isset($this->entityIdentifiers[$oid])) {
1200
            throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'scheduling for update');
1201
        }
1202
1203 1
        if (isset($this->entityDeletions[$oid])) {
1204
            throw ORMInvalidArgumentException::entityIsRemoved($entity, 'schedule for update');
1205
        }
1206
1207 1
        if (! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
1208 1
            $this->entityUpdates[$oid] = $entity;
1209
        }
1210 1
    }
1211
1212
    /**
1213
     * INTERNAL:
1214
     * Schedules an extra update that will be executed immediately after the
1215
     * regular entity updates within the currently running commit cycle.
1216
     *
1217
     * Extra updates for entities are stored as (entity, changeset) tuples.
1218
     *
1219
     * @param object  $entity    The entity for which to schedule an extra update.
1220
     * @param mixed[] $changeset The changeset of the entity (what to update).
1221
     *
1222
     * @ignore
1223
     */
1224 29
    public function scheduleExtraUpdate($entity, array $changeset) : void
1225
    {
1226 29
        $oid         = spl_object_id($entity);
1227 29
        $extraUpdate = [$entity, $changeset];
1228
1229 29
        if (isset($this->extraUpdates[$oid])) {
1230 1
            [$unused, $changeset2] = $this->extraUpdates[$oid];
1231
1232 1
            $extraUpdate = [$entity, $changeset + $changeset2];
1233
        }
1234
1235 29
        $this->extraUpdates[$oid] = $extraUpdate;
1236 29
    }
1237
1238
    /**
1239
     * Checks whether an entity is registered as dirty in the unit of work.
1240
     * Note: Is not very useful currently as dirty entities are only registered
1241
     * at commit time.
1242
     *
1243
     * @param object $entity
1244
     */
1245
    public function isScheduledForUpdate($entity) : bool
1246
    {
1247
        return isset($this->entityUpdates[spl_object_id($entity)]);
1248
    }
1249
1250
    /**
1251
     * Checks whether an entity is registered to be checked in the unit of work.
1252
     *
1253
     * @param object $entity
1254
     */
1255 2
    public function isScheduledForDirtyCheck($entity) : bool
1256
    {
1257 2
        $rootEntityName = $this->em->getClassMetadata(get_class($entity))->getRootClassName();
0 ignored issues
show
Bug introduced by
The method getRootClassName() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

1257
        $rootEntityName = $this->em->getClassMetadata(get_class($entity))->/** @scrutinizer ignore-call */ getRootClassName();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1258
1259 2
        return isset($this->scheduledForSynchronization[$rootEntityName][spl_object_id($entity)]);
1260
    }
1261
1262
    /**
1263
     * INTERNAL:
1264
     * Schedules an entity for deletion.
1265
     *
1266
     * @param object $entity
1267
     */
1268 63
    public function scheduleForDelete($entity)
1269
    {
1270 63
        $oid = spl_object_id($entity);
1271
1272 63
        if (isset($this->entityInsertions[$oid])) {
1273 1
            if ($this->isInIdentityMap($entity)) {
1274
                $this->removeFromIdentityMap($entity);
1275
            }
1276
1277 1
            unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
1278
1279 1
            return; // entity has not been persisted yet, so nothing more to do.
1280
        }
1281
1282 63
        if (! $this->isInIdentityMap($entity)) {
1283 1
            return;
1284
        }
1285
1286 62
        $this->removeFromIdentityMap($entity);
1287
1288 62
        unset($this->entityUpdates[$oid]);
1289
1290 62
        if (! isset($this->entityDeletions[$oid])) {
1291 62
            $this->entityDeletions[$oid] = $entity;
1292 62
            $this->entityStates[$oid]    = self::STATE_REMOVED;
1293
        }
1294 62
    }
1295
1296
    /**
1297
     * Checks whether an entity is registered as removed/deleted with the unit
1298
     * of work.
1299
     *
1300
     * @param object $entity
1301
     *
1302
     * @return bool
1303
     */
1304 13
    public function isScheduledForDelete($entity)
1305
    {
1306 13
        return isset($this->entityDeletions[spl_object_id($entity)]);
1307
    }
1308
1309
    /**
1310
     * Checks whether an entity is scheduled for insertion, update or deletion.
1311
     *
1312
     * @param object $entity
1313
     *
1314
     * @return bool
1315
     */
1316
    public function isEntityScheduled($entity)
1317
    {
1318
        $oid = spl_object_id($entity);
1319
1320
        return isset($this->entityInsertions[$oid])
1321
            || isset($this->entityUpdates[$oid])
1322
            || isset($this->entityDeletions[$oid]);
1323
    }
1324
1325
    /**
1326
     * INTERNAL:
1327
     * Registers an entity in the identity map.
1328
     * Note that entities in a hierarchy are registered with the class name of
1329
     * the root entity.
1330
     *
1331
     * @param object $entity The entity to register.
1332
     *
1333
     * @return bool  TRUE if the registration was successful, FALSE if the identity of
1334
     *               the entity in question is already managed.
1335
     *
1336
     * @throws ORMInvalidArgumentException
1337
     *
1338
     * @ignore
1339
     */
1340 1101
    public function addToIdentityMap($entity)
1341
    {
1342 1101
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1343 1101
        $identifier    = $this->entityIdentifiers[spl_object_id($entity)];
1344
1345 1101
        if (empty($identifier) || in_array(null, $identifier, true)) {
1346 6
            throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->getClassName(), $entity);
1347
        }
1348
1349 1095
        $idHash    = implode(' ', $identifier);
1350 1095
        $className = $classMetadata->getRootClassName();
1351
1352 1095
        if (isset($this->identityMap[$className][$idHash])) {
1353 31
            return false;
1354
        }
1355
1356 1095
        $this->identityMap[$className][$idHash] = $entity;
1357
1358 1095
        return true;
1359
    }
1360
1361
    /**
1362
     * Gets the state of an entity with regard to the current unit of work.
1363
     *
1364
     * @param object   $entity
1365
     * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
1366
     *                         This parameter can be set to improve performance of entity state detection
1367
     *                         by potentially avoiding a database lookup if the distinction between NEW and DETACHED
1368
     *                         is either known or does not matter for the caller of the method.
1369
     *
1370
     * @return int The entity state.
1371
     */
1372 1041
    public function getEntityState($entity, $assume = null)
1373
    {
1374 1041
        $oid = spl_object_id($entity);
1375
1376 1041
        if (isset($this->entityStates[$oid])) {
1377 751
            return $this->entityStates[$oid];
1378
        }
1379
1380 1036
        if ($assume !== null) {
1381 1033
            return $assume;
1382
        }
1383
1384
        // State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
1385
        // Note that you can not remember the NEW or DETACHED state in _entityStates since
1386
        // the UoW does not hold references to such objects and the object hash can be reused.
1387
        // More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
1388 8
        $class     = $this->em->getClassMetadata(get_class($entity));
1389 8
        $persister = $this->getEntityPersister($class->getClassName());
1390 8
        $id        = $persister->getIdentifier($entity);
1391
1392 8
        if (! $id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
1393 3
            return self::STATE_NEW;
1394
        }
1395
1396 6
        $flatId = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $id);
1397
1398 6
        if ($class->isIdentifierComposite()
0 ignored issues
show
Bug introduced by
The method isIdentifierComposite() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. Did you maybe mean isIdentifier()? ( Ignorable by Annotation )

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

1398
        if ($class->/** @scrutinizer ignore-call */ isIdentifierComposite()

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1399 5
            || ! $class->getProperty($class->getSingleIdentifierFieldName()) instanceof FieldMetadata
0 ignored issues
show
Bug introduced by
The method getSingleIdentifierFieldName() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

1399
            || ! $class->getProperty($class->/** @scrutinizer ignore-call */ getSingleIdentifierFieldName()) instanceof FieldMetadata

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1400 6
            || ! $class->getProperty($class->getSingleIdentifierFieldName())->hasValueGenerator()
1401
        ) {
1402
            // Check for a version field, if available, to avoid a db lookup.
1403 5
            if ($class->isVersioned()) {
1404 1
                return $class->versionProperty->getValue($entity)
0 ignored issues
show
Bug introduced by
Accessing versionProperty on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1405
                    ? self::STATE_DETACHED
1406 1
                    : self::STATE_NEW;
1407
            }
1408
1409
            // Last try before db lookup: check the identity map.
1410 4
            if ($this->tryGetById($flatId, $class->getRootClassName())) {
1411 1
                return self::STATE_DETACHED;
1412
            }
1413
1414
            // db lookup
1415 4
            if ($this->getEntityPersister($class->getClassName())->exists($entity)) {
1416
                return self::STATE_DETACHED;
1417
            }
1418
1419 4
            return self::STATE_NEW;
1420
        }
1421
1422 1
        if ($class->isIdentifierComposite()
1423 1
            || ! $class->getProperty($class->getSingleIdentifierFieldName()) instanceof FieldMetadata
1424 1
            || ! $class->getValueGenerationPlan()->containsDeferred()) {
0 ignored issues
show
Bug introduced by
The method getValueGenerationPlan() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

1424
            || ! $class->/** @scrutinizer ignore-call */ getValueGenerationPlan()->containsDeferred()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1425
            // if we have a pre insert generator we can't be sure that having an id
1426
            // really means that the entity exists. We have to verify this through
1427
            // the last resort: a db lookup
1428
1429
            // Last try before db lookup: check the identity map.
1430
            if ($this->tryGetById($flatId, $class->getRootClassName())) {
1431
                return self::STATE_DETACHED;
1432
            }
1433
1434
            // db lookup
1435
            if ($this->getEntityPersister($class->getClassName())->exists($entity)) {
1436
                return self::STATE_DETACHED;
1437
            }
1438
1439
            return self::STATE_NEW;
1440
        }
1441
1442 1
        return self::STATE_DETACHED;
1443
    }
1444
1445
    /**
1446
     * INTERNAL:
1447
     * Removes an entity from the identity map. This effectively detaches the
1448
     * entity from the persistence management of Doctrine.
1449
     *
1450
     * @param object $entity
1451
     *
1452
     * @return bool
1453
     *
1454
     * @throws ORMInvalidArgumentException
1455
     *
1456
     * @ignore
1457
     */
1458 62
    public function removeFromIdentityMap($entity)
1459
    {
1460 62
        $oid           = spl_object_id($entity);
1461 62
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1462 62
        $idHash        = implode(' ', $this->entityIdentifiers[$oid]);
1463
1464 62
        if ($idHash === '') {
1465
            throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'remove from identity map');
1466
        }
1467
1468 62
        $className = $classMetadata->getRootClassName();
1469
1470 62
        if (isset($this->identityMap[$className][$idHash])) {
1471 62
            unset($this->identityMap[$className][$idHash], $this->readOnlyObjects[$oid]);
1472
1473 62
            return true;
1474
        }
1475
1476
        return false;
1477
    }
1478
1479
    /**
1480
     * INTERNAL:
1481
     * Gets an entity in the identity map by its identifier hash.
1482
     *
1483
     * @param string $idHash
1484
     * @param string $rootClassName
1485
     *
1486
     * @return object
1487
     *
1488
     * @ignore
1489
     */
1490 6
    public function getByIdHash($idHash, $rootClassName)
1491
    {
1492 6
        return $this->identityMap[$rootClassName][$idHash];
1493
    }
1494
1495
    /**
1496
     * INTERNAL:
1497
     * Tries to get an entity by its identifier hash. If no entity is found for
1498
     * the given hash, FALSE is returned.
1499
     *
1500
     * @param mixed  $idHash        (must be possible to cast it to string)
1501
     * @param string $rootClassName
1502
     *
1503
     * @return object|bool The found entity or FALSE.
1504
     *
1505
     * @ignore
1506
     */
1507
    public function tryGetByIdHash($idHash, $rootClassName)
1508
    {
1509
        $stringIdHash = (string) $idHash;
1510
1511
        return $this->identityMap[$rootClassName][$stringIdHash] ?? false;
1512
    }
1513
1514
    /**
1515
     * Checks whether an entity is registered in the identity map of this UnitOfWork.
1516
     *
1517
     * @param object $entity
1518
     *
1519
     * @return bool
1520
     */
1521 147
    public function isInIdentityMap($entity)
1522
    {
1523 147
        $oid = spl_object_id($entity);
1524
1525 147
        if (empty($this->entityIdentifiers[$oid])) {
1526 23
            return false;
1527
        }
1528
1529 133
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1530 133
        $idHash        = implode(' ', $this->entityIdentifiers[$oid]);
1531
1532 133
        return isset($this->identityMap[$classMetadata->getRootClassName()][$idHash]);
1533
    }
1534
1535
    /**
1536
     * INTERNAL:
1537
     * Checks whether an identifier hash exists in the identity map.
1538
     *
1539
     * @param string $idHash
1540
     * @param string $rootClassName
1541
     *
1542
     * @return bool
1543
     *
1544
     * @ignore
1545
     */
1546
    public function containsIdHash($idHash, $rootClassName)
1547
    {
1548
        return isset($this->identityMap[$rootClassName][$idHash]);
1549
    }
1550
1551
    /**
1552
     * Persists an entity as part of the current unit of work.
1553
     *
1554
     * @param object $entity The entity to persist.
1555
     */
1556 1033
    public function persist($entity)
1557
    {
1558 1033
        $visited = [];
1559
1560 1033
        $this->doPersist($entity, $visited);
1561 1026
    }
1562
1563
    /**
1564
     * Persists an entity as part of the current unit of work.
1565
     *
1566
     * This method is internally called during persist() cascades as it tracks
1567
     * the already visited entities to prevent infinite recursions.
1568
     *
1569
     * @param object   $entity  The entity to persist.
1570
     * @param object[] $visited The already visited entities.
1571
     *
1572
     * @throws ORMInvalidArgumentException
1573
     * @throws UnexpectedValueException
1574
     */
1575 1033
    private function doPersist($entity, array &$visited)
1576
    {
1577 1033
        $oid = spl_object_id($entity);
1578
1579 1033
        if (isset($visited[$oid])) {
1580 109
            return; // Prevent infinite recursion
1581
        }
1582
1583 1033
        $visited[$oid] = $entity; // Mark visited
1584
1585 1033
        $class = $this->em->getClassMetadata(get_class($entity));
1586
1587
        // We assume NEW, so DETACHED entities result in an exception on flush (constraint violation).
1588
        // If we would detect DETACHED here we would throw an exception anyway with the same
1589
        // consequences (not recoverable/programming error), so just assuming NEW here
1590
        // lets us avoid some database lookups for entities with natural identifiers.
1591 1033
        $entityState = $this->getEntityState($entity, self::STATE_NEW);
1592
1593
        switch ($entityState) {
1594 1033
            case self::STATE_MANAGED:
1595
                // Nothing to do, except if policy is "deferred explicit"
1596 220
                if ($class->changeTrackingPolicy === ChangeTrackingPolicy::DEFERRED_EXPLICIT) {
0 ignored issues
show
Bug introduced by
Accessing changeTrackingPolicy on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1597 3
                    $this->scheduleForSynchronization($entity);
1598
                }
1599 220
                break;
1600
1601 1033
            case self::STATE_NEW:
1602 1032
                $this->persistNew($class, $entity);
1603 1032
                break;
1604
1605 1
            case self::STATE_REMOVED:
1606
                // Entity becomes managed again
1607 1
                unset($this->entityDeletions[$oid]);
1608 1
                $this->addToIdentityMap($entity);
1609
1610 1
                $this->entityStates[$oid] = self::STATE_MANAGED;
1611 1
                break;
1612
1613
            case self::STATE_DETACHED:
1614
                // Can actually not happen right now since we assume STATE_NEW.
1615
                throw ORMInvalidArgumentException::detachedEntityCannot($entity, 'persisted');
1616
1617
            default:
1618
                throw new UnexpectedValueException(
1619
                    sprintf('Unexpected entity state: %d.%s', $entityState, self::objToStr($entity))
1620
                );
1621
        }
1622
1623 1033
        $this->cascadePersist($entity, $visited);
1624 1026
    }
1625
1626
    /**
1627
     * Deletes an entity as part of the current unit of work.
1628
     *
1629
     * @param object $entity The entity to remove.
1630
     */
1631 62
    public function remove($entity)
1632
    {
1633 62
        $visited = [];
1634
1635 62
        $this->doRemove($entity, $visited);
1636 62
    }
1637
1638
    /**
1639
     * Deletes an entity as part of the current unit of work.
1640
     *
1641
     * This method is internally called during delete() cascades as it tracks
1642
     * the already visited entities to prevent infinite recursions.
1643
     *
1644
     * @param object   $entity  The entity to delete.
1645
     * @param object[] $visited The map of the already visited entities.
1646
     *
1647
     * @throws ORMInvalidArgumentException If the instance is a detached entity.
1648
     * @throws UnexpectedValueException
1649
     */
1650 62
    private function doRemove($entity, array &$visited)
1651
    {
1652 62
        $oid = spl_object_id($entity);
1653
1654 62
        if (isset($visited[$oid])) {
1655 1
            return; // Prevent infinite recursion
1656
        }
1657
1658 62
        $visited[$oid] = $entity; // mark visited
1659
1660
        // Cascade first, because scheduleForDelete() removes the entity from the identity map, which
1661
        // can cause problems when a lazy proxy has to be initialized for the cascade operation.
1662 62
        $this->cascadeRemove($entity, $visited);
1663
1664 62
        $class       = $this->em->getClassMetadata(get_class($entity));
1665 62
        $entityState = $this->getEntityState($entity);
1666
1667
        switch ($entityState) {
1668 62
            case self::STATE_NEW:
1669 62
            case self::STATE_REMOVED:
1670
                // nothing to do
1671 2
                break;
1672
1673 62
            case self::STATE_MANAGED:
1674 62
                $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preRemove);
1675
1676 62
                if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1677 8
                    $this->listenersInvoker->invoke($class, Events::preRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
1678
                }
1679
1680 62
                $this->scheduleForDelete($entity);
1681 62
                break;
1682
1683
            case self::STATE_DETACHED:
1684
                throw ORMInvalidArgumentException::detachedEntityCannot($entity, 'removed');
1685
            default:
1686
                throw new UnexpectedValueException(
1687
                    sprintf('Unexpected entity state: %d.%s', $entityState, self::objToStr($entity))
1688
                );
1689
        }
1690 62
    }
1691
1692
    /**
1693
     * Refreshes the state of the given entity from the database, overwriting
1694
     * any local, unpersisted changes.
1695
     *
1696
     * @param object $entity The entity to refresh.
1697
     *
1698
     * @throws InvalidArgumentException If the entity is not MANAGED.
1699
     */
1700 15
    public function refresh($entity)
1701
    {
1702 15
        $visited = [];
1703
1704 15
        $this->doRefresh($entity, $visited);
1705 15
    }
1706
1707
    /**
1708
     * Executes a refresh operation on an entity.
1709
     *
1710
     * @param object   $entity  The entity to refresh.
1711
     * @param object[] $visited The already visited entities during cascades.
1712
     *
1713
     * @throws ORMInvalidArgumentException If the entity is not MANAGED.
1714
     */
1715 15
    private function doRefresh($entity, array &$visited)
1716
    {
1717 15
        $oid = spl_object_id($entity);
1718
1719 15
        if (isset($visited[$oid])) {
1720
            return; // Prevent infinite recursion
1721
        }
1722
1723 15
        $visited[$oid] = $entity; // mark visited
1724
1725 15
        $class = $this->em->getClassMetadata(get_class($entity));
1726
1727 15
        if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
1728
            throw ORMInvalidArgumentException::entityNotManaged($entity);
1729
        }
1730
1731 15
        $this->getEntityPersister($class->getClassName())->refresh(
1732 15
            array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
1733 15
            $entity
1734
        );
1735
1736 15
        $this->cascadeRefresh($entity, $visited);
1737 15
    }
1738
1739
    /**
1740
     * Cascades a refresh operation to associated entities.
1741
     *
1742
     * @param object   $entity
1743
     * @param object[] $visited
1744
     */
1745 15
    private function cascadeRefresh($entity, array &$visited)
1746
    {
1747 15
        $class = $this->em->getClassMetadata(get_class($entity));
1748
1749 15
        foreach ($class->getDeclaredPropertiesIterator() as $association) {
1750 15
            if (! ($association instanceof AssociationMetadata && in_array('refresh', $association->getCascade(), true))) {
1751 15
                continue;
1752
            }
1753
1754 4
            $relatedEntities = $association->getValue($entity);
1755
1756
            switch (true) {
1757 4
                case $relatedEntities instanceof PersistentCollection:
1758
                    // Unwrap so that foreach() does not initialize
1759 4
                    $relatedEntities = $relatedEntities->unwrap();
1760
                    // break; is commented intentionally!
1761
1762
                case $relatedEntities instanceof Collection:
1763
                case is_array($relatedEntities):
1764 4
                    foreach ($relatedEntities as $relatedEntity) {
1765
                        $this->doRefresh($relatedEntity, $visited);
1766
                    }
1767 4
                    break;
1768
1769
                case $relatedEntities !== null:
1770
                    $this->doRefresh($relatedEntities, $visited);
1771
                    break;
1772
1773
                default:
1774
                    // Do nothing
1775
            }
1776
        }
1777 15
    }
1778
1779
    /**
1780
     * Cascades the save operation to associated entities.
1781
     *
1782
     * @param object   $entity
1783
     * @param object[] $visited
1784
     *
1785
     * @throws ORMInvalidArgumentException
1786
     */
1787 1033
    private function cascadePersist($entity, array &$visited)
1788
    {
1789 1033
        $class = $this->em->getClassMetadata(get_class($entity));
1790
1791 1033
        if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
1792
            // nothing to do - proxy is not initialized, therefore we don't do anything with it
1793 1
            return;
1794
        }
1795
1796 1033
        foreach ($class->getDeclaredPropertiesIterator() as $association) {
1797 1033
            if (! ($association instanceof AssociationMetadata && in_array('persist', $association->getCascade(), true))) {
1798 1033
                continue;
1799
            }
1800
1801
            /** @var AssociationMetadata $association */
1802 647
            $relatedEntities = $association->getValue($entity);
1803 647
            $targetEntity    = $association->getTargetEntity();
1804
1805
            switch (true) {
1806 647
                case $relatedEntities instanceof PersistentCollection:
1807
                    // Unwrap so that foreach() does not initialize
1808 13
                    $relatedEntities = $relatedEntities->unwrap();
1809
                    // break; is commented intentionally!
1810
1811 647
                case $relatedEntities instanceof Collection:
1812 584
                case is_array($relatedEntities):
1813 542
                    if (! ($association instanceof ToManyAssociationMetadata)) {
1814 3
                        throw ORMInvalidArgumentException::invalidAssociation(
1815 3
                            $this->em->getClassMetadata($targetEntity),
1816 3
                            $association,
1817 3
                            $relatedEntities
1818
                        );
1819
                    }
1820
1821 539
                    foreach ($relatedEntities as $relatedEntity) {
1822 283
                        $this->doPersist($relatedEntity, $visited);
1823
                    }
1824
1825 539
                    break;
1826
1827 573
                case $relatedEntities !== null:
1828 241
                    if (! $relatedEntities instanceof $targetEntity) {
1829 4
                        throw ORMInvalidArgumentException::invalidAssociation(
1830 4
                            $this->em->getClassMetadata($targetEntity),
1831 4
                            $association,
1832 4
                            $relatedEntities
1833
                        );
1834
                    }
1835
1836 237
                    $this->doPersist($relatedEntities, $visited);
1837 237
                    break;
1838
1839
                default:
1840
                    // Do nothing
1841
            }
1842
        }
1843 1026
    }
1844
1845
    /**
1846
     * Cascades the delete operation to associated entities.
1847
     *
1848
     * @param object   $entity
1849
     * @param object[] $visited
1850
     */
1851 62
    private function cascadeRemove($entity, array &$visited)
1852
    {
1853 62
        $entitiesToCascade = [];
1854 62
        $class             = $this->em->getClassMetadata(get_class($entity));
1855
1856 62
        foreach ($class->getDeclaredPropertiesIterator() as $association) {
1857 62
            if (! ($association instanceof AssociationMetadata && in_array('remove', $association->getCascade(), true))) {
1858 62
                continue;
1859
            }
1860
1861 25
            if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
1862 6
                $entity->initializeProxy();
1863
            }
1864
1865 25
            $relatedEntities = $association->getValue($entity);
1866
1867
            switch (true) {
1868 25
                case $relatedEntities instanceof Collection:
1869 18
                case is_array($relatedEntities):
1870
                    // If its a PersistentCollection initialization is intended! No unwrap!
1871 20
                    foreach ($relatedEntities as $relatedEntity) {
1872 10
                        $entitiesToCascade[] = $relatedEntity;
1873
                    }
1874 20
                    break;
1875
1876 18
                case $relatedEntities !== null:
1877 7
                    $entitiesToCascade[] = $relatedEntities;
1878 7
                    break;
1879
1880
                default:
1881
                    // Do nothing
1882
            }
1883
        }
1884
1885 62
        foreach ($entitiesToCascade as $relatedEntity) {
1886 16
            $this->doRemove($relatedEntity, $visited);
1887
        }
1888 62
    }
1889
1890
    /**
1891
     * Acquire a lock on the given entity.
1892
     *
1893
     * @param object $entity
1894
     * @param int    $lockMode
1895
     * @param int    $lockVersion
1896
     *
1897
     * @throws ORMInvalidArgumentException
1898
     * @throws TransactionRequiredException
1899
     * @throws OptimisticLockException
1900
     * @throws InvalidArgumentException
1901
     */
1902 10
    public function lock($entity, $lockMode, $lockVersion = null)
1903
    {
1904 10
        if ($entity === null) {
1905 1
            throw new InvalidArgumentException('No entity passed to UnitOfWork#lock().');
1906
        }
1907
1908 9
        if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) {
1909 1
            throw ORMInvalidArgumentException::entityNotManaged($entity);
1910
        }
1911
1912 8
        $class = $this->em->getClassMetadata(get_class($entity));
1913
1914
        switch (true) {
1915 8
            case $lockMode === LockMode::OPTIMISTIC:
1916 6
                if (! $class->isVersioned()) {
1917 1
                    throw OptimisticLockException::notVersioned($class->getClassName());
1918
                }
1919
1920 5
                if ($lockVersion === null) {
1921 1
                    return;
1922
                }
1923
1924 4
                if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
1925 1
                    $entity->initializeProxy();
1926
                }
1927
1928 4
                $entityVersion = $class->versionProperty->getValue($entity);
0 ignored issues
show
Bug introduced by
Accessing versionProperty on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1929
1930 4
                if ($entityVersion !== $lockVersion) {
1931 2
                    throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion);
1932
                }
1933
1934 2
                break;
1935
1936 2
            case $lockMode === LockMode::NONE:
1937 2
            case $lockMode === LockMode::PESSIMISTIC_READ:
1938 1
            case $lockMode === LockMode::PESSIMISTIC_WRITE:
1939 2
                if (! $this->em->getConnection()->isTransactionActive()) {
1940 2
                    throw TransactionRequiredException::transactionRequired();
1941
                }
1942
1943
                $oid = spl_object_id($entity);
1944
1945
                $this->getEntityPersister($class->getClassName())->lock(
1946
                    array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
1947
                    $lockMode
1948
                );
1949
                break;
1950
1951
            default:
1952
                // Do nothing
1953
        }
1954 2
    }
1955
1956
    /**
1957
     * Clears the UnitOfWork.
1958
     */
1959 1219
    public function clear()
1960
    {
1961 1219
        $this->entityPersisters               =
1962 1219
        $this->collectionPersisters           =
1963 1219
        $this->eagerLoadingEntities           =
1964 1219
        $this->identityMap                    =
1965 1219
        $this->entityIdentifiers              =
1966 1219
        $this->originalEntityData             =
1967 1219
        $this->entityChangeSets               =
1968 1219
        $this->entityStates                   =
1969 1219
        $this->scheduledForSynchronization    =
1970 1219
        $this->entityInsertions               =
1971 1219
        $this->entityUpdates                  =
1972 1219
        $this->entityDeletions                =
1973 1219
        $this->collectionDeletions            =
1974 1219
        $this->collectionUpdates              =
1975 1219
        $this->extraUpdates                   =
1976 1219
        $this->readOnlyObjects                =
1977 1219
        $this->visitedCollections             =
1978 1219
        $this->nonCascadedNewDetectedEntities =
1979 1219
        $this->orphanRemovals                 = [];
1980 1219
    }
1981
1982
    /**
1983
     * INTERNAL:
1984
     * Schedules an orphaned entity for removal. The remove() operation will be
1985
     * invoked on that entity at the beginning of the next commit of this
1986
     * UnitOfWork.
1987
     *
1988
     * @param object $entity
1989
     *
1990
     * @ignore
1991
     */
1992 16
    public function scheduleOrphanRemoval($entity)
1993
    {
1994 16
        $this->orphanRemovals[spl_object_id($entity)] = $entity;
1995 16
    }
1996
1997
    /**
1998
     * INTERNAL:
1999
     * Cancels a previously scheduled orphan removal.
2000
     *
2001
     * @param object $entity
2002
     *
2003
     * @ignore
2004
     */
2005 111
    public function cancelOrphanRemoval($entity)
2006
    {
2007 111
        unset($this->orphanRemovals[spl_object_id($entity)]);
2008 111
    }
2009
2010
    /**
2011
     * INTERNAL:
2012
     * Schedules a complete collection for removal when this UnitOfWork commits.
2013
     */
2014 22
    public function scheduleCollectionDeletion(PersistentCollection $coll)
2015
    {
2016 22
        $coid = spl_object_id($coll);
2017
2018
        // TODO: if $coll is already scheduled for recreation ... what to do?
2019
        // Just remove $coll from the scheduled recreations?
2020 22
        unset($this->collectionUpdates[$coid]);
2021
2022 22
        $this->collectionDeletions[$coid] = $coll;
2023 22
    }
2024
2025
    /**
2026
     * @return bool
2027
     */
2028 8
    public function isCollectionScheduledForDeletion(PersistentCollection $coll)
2029
    {
2030 8
        return isset($this->collectionDeletions[spl_object_id($coll)]);
2031
    }
2032
2033
    /**
2034
     * INTERNAL:
2035
     * Creates a new instance of the mapped class, without invoking the constructor.
2036
     * This is only meant to be used internally, and should not be consumed by end users.
2037
     *
2038
     * @return EntityManagerAware|object
2039
     *
2040
     * @ignore
2041
     */
2042 665
    public function newInstance(ClassMetadata $class)
2043
    {
2044 665
        $entity = $this->instantiator->instantiate($class->getClassName());
2045
2046 665
        if ($entity instanceof EntityManagerAware) {
2047 5
            $entity->injectEntityManager($this->em, $class);
2048
        }
2049
2050 665
        return $entity;
2051
    }
2052
2053
    /**
2054
     * INTERNAL:
2055
     * Creates an entity. Used for reconstitution of persistent entities.
2056
     *
2057
     * {@internal Highly performance-sensitive method. }}
2058
     *
2059
     * @param string  $className The name of the entity class.
2060
     * @param mixed[] $data      The data for the entity.
2061
     * @param mixed[] $hints     Any hints to account for during reconstitution/lookup of the entity.
2062
     *
2063
     * @return object The managed entity instance.
2064
     *
2065
     * @ignore
2066
     * @todo Rename: getOrCreateEntity
2067
     */
2068 802
    public function createEntity($className, array $data, &$hints = [])
2069
    {
2070 802
        $class  = $this->em->getClassMetadata($className);
2071 802
        $id     = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $data);
2072 802
        $idHash = implode(' ', $id);
2073
2074 802
        if (isset($this->identityMap[$class->getRootClassName()][$idHash])) {
2075 305
            $entity = $this->identityMap[$class->getRootClassName()][$idHash];
2076 305
            $oid    = spl_object_id($entity);
2077
2078 305
            if (isset($hints[Query::HINT_REFRESH], $hints[Query::HINT_REFRESH_ENTITY])) {
2079 65
                $unmanagedProxy = $hints[Query::HINT_REFRESH_ENTITY];
2080 65
                if ($unmanagedProxy !== $entity
2081 65
                    && $unmanagedProxy instanceof GhostObjectInterface
2082 65
                    && $this->isIdentifierEquals($unmanagedProxy, $entity)
2083
                ) {
2084
                    // We will hydrate the given un-managed proxy anyway:
2085
                    // continue work, but consider it the entity from now on
2086 5
                    $entity = $unmanagedProxy;
2087
                }
2088
            }
2089
2090 305
            if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
2091 21
                $entity->setProxyInitializer(null);
2092
2093 21
                if ($entity instanceof NotifyPropertyChanged) {
2094 21
                    $entity->addPropertyChangedListener($this);
2095
                }
2096
            } else {
2097 291
                if (! isset($hints[Query::HINT_REFRESH])
2098 291
                    || (isset($hints[Query::HINT_REFRESH_ENTITY]) && $hints[Query::HINT_REFRESH_ENTITY] !== $entity)) {
2099 229
                    return $entity;
2100
                }
2101
            }
2102
2103
            // inject EntityManager upon refresh.
2104 103
            if ($entity instanceof EntityManagerAware) {
2105 3
                $entity->injectEntityManager($this->em, $class);
2106
            }
2107
2108 103
            $this->originalEntityData[$oid] = $data;
2109
        } else {
2110 662
            $entity = $this->newInstance($class);
2111 662
            $oid    = spl_object_id($entity);
2112
2113 662
            $this->entityIdentifiers[$oid]  = $id;
2114 662
            $this->entityStates[$oid]       = self::STATE_MANAGED;
2115 662
            $this->originalEntityData[$oid] = $data;
2116
2117 662
            $this->identityMap[$class->getRootClassName()][$idHash] = $entity;
2118
        }
2119
2120 695
        if ($entity instanceof NotifyPropertyChanged) {
2121 3
            $entity->addPropertyChangedListener($this);
2122
        }
2123
2124 695
        foreach ($data as $field => $value) {
2125 695
            $property = $class->getProperty($field);
2126
2127 695
            if ($property instanceof FieldMetadata) {
2128 693
                $property->setValue($entity, $value);
2129
            }
2130
        }
2131
2132
        // Loading the entity right here, if its in the eager loading map get rid of it there.
2133 695
        unset($this->eagerLoadingEntities[$class->getRootClassName()][$idHash]);
2134
2135 695
        if (isset($this->eagerLoadingEntities[$class->getRootClassName()]) && ! $this->eagerLoadingEntities[$class->getRootClassName()]) {
2136
            unset($this->eagerLoadingEntities[$class->getRootClassName()]);
2137
        }
2138
2139
        // Properly initialize any unfetched associations, if partial objects are not allowed.
2140 695
        if (isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
2141 34
            return $entity;
2142
        }
2143
2144 661
        foreach ($class->getDeclaredPropertiesIterator() as $field => $association) {
2145 661
            if (! ($association instanceof AssociationMetadata)) {
2146 661
                continue;
2147
            }
2148
2149
            // Check if the association is not among the fetch-joined associations already.
2150 565
            if (isset($hints['fetchAlias'], $hints['fetched'][$hints['fetchAlias']][$field])) {
2151 243
                continue;
2152
            }
2153
2154 542
            $targetEntity = $association->getTargetEntity();
2155 542
            $targetClass  = $this->em->getClassMetadata($targetEntity);
2156
2157 542
            if ($association instanceof ToManyAssociationMetadata) {
2158
                // Ignore if its a cached collection
2159 463
                if (isset($hints[Query::HINT_CACHE_ENABLED]) &&
2160 463
                    $association->getValue($entity) instanceof PersistentCollection) {
2161
                    continue;
2162
                }
2163
2164 463
                $hasDataField = isset($data[$field]);
2165
2166
                // use the given collection
2167 463
                if ($hasDataField && $data[$field] instanceof PersistentCollection) {
2168
                    $data[$field]->setOwner($entity, $association);
2169
2170
                    $association->setValue($entity, $data[$field]);
2171
2172
                    $this->originalEntityData[$oid][$field] = $data[$field];
2173
2174
                    continue;
2175
                }
2176
2177
                // Inject collection
2178 463
                $pColl = $association->wrap($entity, $hasDataField ? $data[$field] : [], $this->em);
2179
2180 463
                $pColl->setInitialized($hasDataField);
2181
2182 463
                $association->setValue($entity, $pColl);
2183
2184 463
                if ($association->getFetchMode() === FetchMode::EAGER) {
2185 4
                    $this->loadCollection($pColl);
2186 4
                    $pColl->takeSnapshot();
2187
                }
2188
2189 463
                $this->originalEntityData[$oid][$field] = $pColl;
2190
2191 463
                continue;
2192
            }
2193
2194 469
            if (! $association->isOwningSide()) {
2195
                // use the given entity association
2196 66
                if (isset($data[$field]) && is_object($data[$field]) &&
2197 66
                    isset($this->entityStates[spl_object_id($data[$field])])) {
2198 3
                    $inverseAssociation = $targetClass->getProperty($association->getMappedBy());
2199
2200 3
                    $association->setValue($entity, $data[$field]);
2201 3
                    $inverseAssociation->setValue($data[$field], $entity);
2202
2203 3
                    $this->originalEntityData[$oid][$field] = $data[$field];
2204
2205 3
                    continue;
2206
                }
2207
2208
                // Inverse side of x-to-one can never be lazy
2209 63
                $persister = $this->getEntityPersister($targetEntity);
2210
2211 63
                $association->setValue($entity, $persister->loadToOneEntity($association, $entity));
2212
2213 63
                continue;
2214
            }
2215
2216
            // use the entity association
2217 469
            if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_id($data[$field])])) {
2218 38
                $association->setValue($entity, $data[$field]);
2219
2220 38
                $this->originalEntityData[$oid][$field] = $data[$field];
2221
2222 38
                continue;
2223
            }
2224
2225 462
            $associatedId = [];
2226
2227
            // TODO: Is this even computed right in all cases of composite keys?
2228 462
            foreach ($association->getJoinColumns() as $joinColumn) {
0 ignored issues
show
Bug introduced by
The method getJoinColumns() does not exist on Doctrine\ORM\Mapping\AssociationMetadata. It seems like you code against a sub-type of Doctrine\ORM\Mapping\AssociationMetadata such as Doctrine\ORM\Mapping\ToOneAssociationMetadata. ( Ignorable by Annotation )

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

2228
            foreach ($association->/** @scrutinizer ignore-call */ getJoinColumns() as $joinColumn) {
Loading history...
2229
                /** @var JoinColumnMetadata $joinColumn */
2230 462
                $joinColumnName  = $joinColumn->getColumnName();
2231 462
                $joinColumnValue = $data[$joinColumnName] ?? null;
2232 462
                $targetField     = $targetClass->fieldNames[$joinColumn->getReferencedColumnName()];
0 ignored issues
show
Bug introduced by
Accessing fieldNames on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2233
2234 462
                if ($joinColumnValue === null && in_array($targetField, $targetClass->identifier, true)) {
0 ignored issues
show
Bug introduced by
Accessing identifier on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2235
                    // the missing key is part of target's entity primary key
2236 266
                    $associatedId = [];
2237
2238 266
                    continue;
2239
                }
2240
2241 284
                $associatedId[$targetField] = $joinColumnValue;
2242
            }
2243
2244 462
            if (! $associatedId) {
2245
                // Foreign key is NULL
2246 266
                $association->setValue($entity, null);
2247 266
                $this->originalEntityData[$oid][$field] = null;
2248
2249 266
                continue;
2250
            }
2251
2252
            // @todo guilhermeblanco Can we remove the need of this somehow?
2253 284
            if (! isset($hints['fetchMode'][$class->getClassName()][$field])) {
2254 281
                $hints['fetchMode'][$class->getClassName()][$field] = $association->getFetchMode();
2255
            }
2256
2257
            // Foreign key is set
2258
            // Check identity map first
2259
            // FIXME: Can break easily with composite keys if join column values are in
2260
            //        wrong order. The correct order is the one in ClassMetadata#identifier.
2261 284
            $relatedIdHash = implode(' ', $associatedId);
2262
2263
            switch (true) {
2264 284
                case isset($this->identityMap[$targetClass->getRootClassName()][$relatedIdHash]):
2265 168
                    $newValue = $this->identityMap[$targetClass->getRootClassName()][$relatedIdHash];
2266
2267
                    // If this is an uninitialized proxy, we are deferring eager loads,
2268
                    // this association is marked as eager fetch, and its an uninitialized proxy (wtf!)
2269
                    // then we can append this entity for eager loading!
2270 168
                    if (! $targetClass->isIdentifierComposite() &&
2271 168
                        $newValue instanceof GhostObjectInterface &&
2272 168
                        isset($hints[self::HINT_DEFEREAGERLOAD]) &&
2273 168
                        $hints['fetchMode'][$class->getClassName()][$field] === FetchMode::EAGER &&
2274 168
                        ! $newValue->isProxyInitialized()
2275
                    ) {
2276
                        $this->eagerLoadingEntities[$targetClass->getRootClassName()][$relatedIdHash] = current($associatedId);
2277
                    }
2278
2279 168
                    break;
2280
2281 190
                case $targetClass->getSubClasses():
2282
                    // If it might be a subtype, it can not be lazy. There isn't even
2283
                    // a way to solve this with deferred eager loading, which means putting
2284
                    // an entity with subclasses at a *-to-one location is really bad! (performance-wise)
2285 29
                    $persister = $this->getEntityPersister($targetEntity);
2286 29
                    $newValue  = $persister->loadToOneEntity($association, $entity, $associatedId);
2287 29
                    break;
2288
2289
                default:
2290
                    // Proxies do not carry any kind of original entity data until they're fully loaded/initialized
2291 163
                    $managedData = [];
2292
2293 163
                    $normalizedAssociatedId = $this->normalizeIdentifier->__invoke(
2294 163
                        $this->em,
2295 163
                        $targetClass,
2296 163
                        $associatedId
2297
                    );
2298
2299
                    switch (true) {
2300
                        // We are negating the condition here. Other cases will assume it is valid!
2301 163
                        case $hints['fetchMode'][$class->getClassName()][$field] !== FetchMode::EAGER:
2302 156
                            $newValue = $this->em->getProxyFactory()->getProxy($targetClass, $normalizedAssociatedId);
2303 156
                            break;
2304
2305
                        // Deferred eager load only works for single identifier classes
2306 7
                        case isset($hints[self::HINT_DEFEREAGERLOAD]) && ! $targetClass->isIdentifierComposite():
2307
                            // TODO: Is there a faster approach?
2308 7
                            $this->eagerLoadingEntities[$targetClass->getRootClassName()][$relatedIdHash] = current($normalizedAssociatedId);
2309
2310 7
                            $newValue = $this->em->getProxyFactory()->getProxy($targetClass, $normalizedAssociatedId);
2311 7
                            break;
2312
2313
                        default:
2314
                            // TODO: This is very imperformant, ignore it?
2315
                            $newValue = $this->em->find($targetEntity, $normalizedAssociatedId);
2316
                            // Needed to re-assign original entity data for freshly loaded entity
2317
                            $managedData = $this->originalEntityData[spl_object_id($newValue)];
2318
                            break;
2319
                    }
2320
2321
                    // @TODO using `$associatedId` here seems to be risky.
2322 163
                    $this->registerManaged($newValue, $associatedId, $managedData);
2323
2324 163
                    break;
2325
            }
2326
2327 284
            $this->originalEntityData[$oid][$field] = $newValue;
2328 284
            $association->setValue($entity, $newValue);
2329
2330 284
            if ($association->getInversedBy()
2331 284
                && $association instanceof OneToOneAssociationMetadata
2332
                // @TODO refactor this
2333
                // we don't want to set any values in un-initialized proxies
2334
                && ! (
2335 56
                    $newValue instanceof GhostObjectInterface
2336 284
                    && ! $newValue->isProxyInitialized()
2337
                )
2338
            ) {
2339 19
                $inverseAssociation = $targetClass->getProperty($association->getInversedBy());
2340
2341 19
                $inverseAssociation->setValue($newValue, $entity);
2342
            }
2343
        }
2344
2345
        // defer invoking of postLoad event to hydration complete step
2346 661
        $this->hydrationCompleteHandler->deferPostLoadInvoking($class, $entity);
2347
2348 661
        return $entity;
2349
    }
2350
2351 862
    public function triggerEagerLoads()
2352
    {
2353 862
        if (! $this->eagerLoadingEntities) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->eagerLoadingEntities of type array<mixed,array<mixed,array<mixed,mixed>>> is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
2354 862
            return;
2355
        }
2356
2357
        // avoid infinite recursion
2358 7
        $eagerLoadingEntities       = $this->eagerLoadingEntities;
2359 7
        $this->eagerLoadingEntities = [];
2360
2361 7
        foreach ($eagerLoadingEntities as $entityName => $ids) {
2362 7
            if (! $ids) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ids of type array<mixed,array<mixed,mixed>> is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
2363
                continue;
2364
            }
2365
2366 7
            $class = $this->em->getClassMetadata($entityName);
2367
2368 7
            $this->getEntityPersister($entityName)->loadAll(
2369 7
                array_combine($class->identifier, [array_values($ids)])
0 ignored issues
show
Bug introduced by
Accessing identifier on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2370
            );
2371
        }
2372 7
    }
2373
2374
    /**
2375
     * Initializes (loads) an uninitialized persistent collection of an entity.
2376
     *
2377
     * @param PersistentCollection $collection The collection to initialize.
2378
     *
2379
     * @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733.
2380
     */
2381 139
    public function loadCollection(PersistentCollection $collection)
2382
    {
2383 139
        $association = $collection->getMapping();
2384 139
        $persister   = $this->getEntityPersister($association->getTargetEntity());
2385
2386 139
        if ($association instanceof OneToManyAssociationMetadata) {
2387 74
            $persister->loadOneToManyCollection($association, $collection->getOwner(), $collection);
2388
        } else {
2389 75
            $persister->loadManyToManyCollection($association, $collection->getOwner(), $collection);
2390
        }
2391
2392 139
        $collection->setInitialized(true);
2393 139
    }
2394
2395
    /**
2396
     * Gets the identity map of the UnitOfWork.
2397
     *
2398
     * @return object[]
2399
     */
2400 1
    public function getIdentityMap()
2401
    {
2402 1
        return $this->identityMap;
2403
    }
2404
2405
    /**
2406
     * Gets the original data of an entity. The original data is the data that was
2407
     * present at the time the entity was reconstituted from the database.
2408
     *
2409
     * @param object $entity
2410
     *
2411
     * @return mixed[]
2412
     */
2413 121
    public function getOriginalEntityData($entity)
2414
    {
2415 121
        $oid = spl_object_id($entity);
2416
2417 121
        return $this->originalEntityData[$oid] ?? [];
2418
    }
2419
2420
    /**
2421
     * @param object  $entity
2422
     * @param mixed[] $data
2423
     *
2424
     * @ignore
2425
     */
2426
    public function setOriginalEntityData($entity, array $data)
2427
    {
2428
        $this->originalEntityData[spl_object_id($entity)] = $data;
2429
    }
2430
2431
    /**
2432
     * INTERNAL:
2433
     * Sets a property value of the original data array of an entity.
2434
     *
2435
     * @param string $oid
2436
     * @param string $property
2437
     * @param mixed  $value
2438
     *
2439
     * @ignore
2440
     */
2441 301
    public function setOriginalEntityProperty($oid, $property, $value)
2442
    {
2443 301
        $this->originalEntityData[$oid][$property] = $value;
2444 301
    }
2445
2446
    /**
2447
     * Gets the identifier of an entity.
2448
     * The returned value is always an array of identifier values. If the entity
2449
     * has a composite identifier then the identifier values are in the same
2450
     * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
2451
     *
2452
     * @param object $entity
2453
     *
2454
     * @return mixed[] The identifier values.
2455
     */
2456 568
    public function getEntityIdentifier($entity)
2457
    {
2458 568
        return $this->entityIdentifiers[spl_object_id($entity)];
2459
    }
2460
2461
    /**
2462
     * Processes an entity instance to extract their identifier values.
2463
     *
2464
     * @param object $entity The entity instance.
2465
     *
2466
     * @return mixed A scalar value.
2467
     *
2468
     * @throws ORMInvalidArgumentException
2469
     */
2470 70
    public function getSingleIdentifierValue($entity)
2471
    {
2472 70
        $class     = $this->em->getClassMetadata(get_class($entity));
2473 70
        $persister = $this->getEntityPersister($class->getClassName());
2474
2475 70
        if ($class->isIdentifierComposite()) {
2476
            throw ORMInvalidArgumentException::invalidCompositeIdentifier();
2477
        }
2478
2479 70
        $values = $this->isInIdentityMap($entity)
2480 58
            ? $this->getEntityIdentifier($entity)
2481 70
            : $persister->getIdentifier($entity);
2482
2483 70
        return $values[$class->identifier[0]] ?? null;
0 ignored issues
show
Bug introduced by
Accessing identifier on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2484
    }
2485
2486
    /**
2487
     * Tries to find an entity with the given identifier in the identity map of
2488
     * this UnitOfWork.
2489
     *
2490
     * @param mixed|mixed[] $id            The entity identifier to look for.
2491
     * @param string        $rootClassName The name of the root class of the mapped entity hierarchy.
2492
     *
2493
     * @return object|bool Returns the entity with the specified identifier if it exists in
2494
     *                     this UnitOfWork, FALSE otherwise.
2495
     */
2496 538
    public function tryGetById($id, $rootClassName)
2497
    {
2498 538
        $idHash = implode(' ', (array) $id);
2499
2500 538
        return $this->identityMap[$rootClassName][$idHash] ?? false;
2501
    }
2502
2503
    /**
2504
     * Schedules an entity for dirty-checking at commit-time.
2505
     *
2506
     * @param object $entity The entity to schedule for dirty-checking.
2507
     */
2508 6
    public function scheduleForSynchronization($entity)
2509
    {
2510 6
        $rootClassName = $this->em->getClassMetadata(get_class($entity))->getRootClassName();
2511
2512 6
        $this->scheduledForSynchronization[$rootClassName][spl_object_id($entity)] = $entity;
2513 6
    }
2514
2515
    /**
2516
     * Checks whether the UnitOfWork has any pending insertions.
2517
     *
2518
     * @return bool TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
2519
     */
2520
    public function hasPendingInsertions()
2521
    {
2522
        return ! empty($this->entityInsertions);
2523
    }
2524
2525
    /**
2526
     * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
2527
     * number of entities in the identity map.
2528
     *
2529
     * @return int
2530
     */
2531 1
    public function size()
2532
    {
2533 1
        return array_sum(array_map('count', $this->identityMap));
2534
    }
2535
2536
    /**
2537
     * Gets the EntityPersister for an Entity.
2538
     *
2539
     * @param string $entityName The name of the Entity.
2540
     *
2541
     * @return EntityPersister
2542
     */
2543 1087
    public function getEntityPersister($entityName)
2544
    {
2545 1087
        if (isset($this->entityPersisters[$entityName])) {
2546 1033
            return $this->entityPersisters[$entityName];
2547
        }
2548
2549 1087
        $class = $this->em->getClassMetadata($entityName);
2550
2551
        switch (true) {
2552 1087
            case $class->inheritanceType === InheritanceType::NONE:
0 ignored issues
show
Bug introduced by
Accessing inheritanceType on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2553 1044
                $persister = new BasicEntityPersister($this->em, $class);
2554 1044
                break;
2555
2556 385
            case $class->inheritanceType === InheritanceType::SINGLE_TABLE:
2557 223
                $persister = new SingleTablePersister($this->em, $class);
2558 223
                break;
2559
2560 355
            case $class->inheritanceType === InheritanceType::JOINED:
2561 355
                $persister = new JoinedSubclassPersister($this->em, $class);
2562 355
                break;
2563
2564
            default:
2565
                throw new RuntimeException('No persister found for entity.');
2566
        }
2567
2568 1087
        if ($this->hasCache && $class->getCache()) {
0 ignored issues
show
Bug introduced by
The method getCache() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

2568
        if ($this->hasCache && $class->/** @scrutinizer ignore-call */ getCache()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
2569 131
            $persister = $this->em->getConfiguration()
2570 131
                ->getSecondLevelCacheConfiguration()
2571 131
                ->getCacheFactory()
2572 131
                ->buildCachedEntityPersister($this->em, $persister, $class);
2573
        }
2574
2575 1087
        $this->entityPersisters[$entityName] = $persister;
2576
2577 1087
        return $this->entityPersisters[$entityName];
2578
    }
2579
2580
    /**
2581
     * Gets a collection persister for a collection-valued association.
2582
     *
2583
     * @return CollectionPersister
2584
     */
2585 565
    public function getCollectionPersister(ToManyAssociationMetadata $association)
2586
    {
2587 565
        $role = $association->getCache()
2588 78
            ? sprintf('%s::%s', $association->getSourceEntity(), $association->getName())
2589 565
            : get_class($association);
2590
2591 565
        if (isset($this->collectionPersisters[$role])) {
2592 431
            return $this->collectionPersisters[$role];
2593
        }
2594
2595 565
        $persister = $association instanceof OneToManyAssociationMetadata
2596 402
            ? new OneToManyPersister($this->em)
2597 565
            : new ManyToManyPersister($this->em);
2598
2599 565
        if ($this->hasCache && $association->getCache()) {
2600 77
            $persister = $this->em->getConfiguration()
2601 77
                ->getSecondLevelCacheConfiguration()
2602 77
                ->getCacheFactory()
2603 77
                ->buildCachedCollectionPersister($this->em, $persister, $association);
2604
        }
2605
2606 565
        $this->collectionPersisters[$role] = $persister;
2607
2608 565
        return $this->collectionPersisters[$role];
2609
    }
2610
2611
    /**
2612
     * INTERNAL:
2613
     * Registers an entity as managed.
2614
     *
2615
     * @param object  $entity The entity.
2616
     * @param mixed[] $id     Map containing identifier field names as key and its associated values.
2617
     * @param mixed[] $data   The original entity data.
2618
     */
2619 291
    public function registerManaged($entity, array $id, array $data)
2620
    {
2621 291
        $isProxy = $entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized();
2622 291
        $oid     = spl_object_id($entity);
2623
2624 291
        $this->entityIdentifiers[$oid]  = $id;
2625 291
        $this->entityStates[$oid]       = self::STATE_MANAGED;
2626 291
        $this->originalEntityData[$oid] = $data;
2627
2628 291
        $this->addToIdentityMap($entity);
2629
2630 285
        if ($entity instanceof NotifyPropertyChanged && ! $isProxy) {
2631 1
            $entity->addPropertyChangedListener($this);
2632
        }
2633 285
    }
2634
2635
    /**
2636
     * INTERNAL:
2637
     * Clears the property changeset of the entity with the given OID.
2638
     *
2639
     * @param string $oid The entity's OID.
2640
     */
2641
    public function clearEntityChangeSet($oid)
2642
    {
2643
        unset($this->entityChangeSets[$oid]);
2644
    }
2645
2646
    /* PropertyChangedListener implementation */
2647
2648
    /**
2649
     * Notifies this UnitOfWork of a property change in an entity.
2650
     *
2651
     * @param object $entity       The entity that owns the property.
2652
     * @param string $propertyName The name of the property that changed.
2653
     * @param mixed  $oldValue     The old value of the property.
2654
     * @param mixed  $newValue     The new value of the property.
2655
     */
2656 3
    public function propertyChanged($entity, $propertyName, $oldValue, $newValue)
2657
    {
2658 3
        $class = $this->em->getClassMetadata(get_class($entity));
2659
2660 3
        if (! $class->getProperty($propertyName)) {
2661
            return; // ignore non-persistent fields
2662
        }
2663
2664 3
        $oid = spl_object_id($entity);
2665
2666
        // Update changeset and mark entity for synchronization
2667 3
        $this->entityChangeSets[$oid][$propertyName] = [$oldValue, $newValue];
2668
2669 3
        if (! isset($this->scheduledForSynchronization[$class->getRootClassName()][$oid])) {
2670 3
            $this->scheduleForSynchronization($entity);
2671
        }
2672 3
    }
2673
2674
    /**
2675
     * Gets the currently scheduled entity insertions in this UnitOfWork.
2676
     *
2677
     * @return object[]
2678
     */
2679 2
    public function getScheduledEntityInsertions()
2680
    {
2681 2
        return $this->entityInsertions;
2682
    }
2683
2684
    /**
2685
     * Gets the currently scheduled entity updates in this UnitOfWork.
2686
     *
2687
     * @return object[]
2688
     */
2689 3
    public function getScheduledEntityUpdates()
2690
    {
2691 3
        return $this->entityUpdates;
2692
    }
2693
2694
    /**
2695
     * Gets the currently scheduled entity deletions in this UnitOfWork.
2696
     *
2697
     * @return object[]
2698
     */
2699 1
    public function getScheduledEntityDeletions()
2700
    {
2701 1
        return $this->entityDeletions;
2702
    }
2703
2704
    /**
2705
     * Gets the currently scheduled complete collection deletions
2706
     *
2707
     * @return Collection[]|object[][]
2708
     */
2709 1
    public function getScheduledCollectionDeletions()
2710
    {
2711 1
        return $this->collectionDeletions;
2712
    }
2713
2714
    /**
2715
     * Gets the currently scheduled collection inserts, updates and deletes.
2716
     *
2717
     * @return Collection[]|object[][]
2718
     */
2719
    public function getScheduledCollectionUpdates()
2720
    {
2721
        return $this->collectionUpdates;
2722
    }
2723
2724
    /**
2725
     * Helper method to initialize a lazy loading proxy or persistent collection.
2726
     *
2727
     * @param object $obj
2728
     */
2729 2
    public function initializeObject($obj)
2730
    {
2731 2
        if ($obj instanceof GhostObjectInterface) {
2732 1
            $obj->initializeProxy();
2733
2734 1
            return;
2735
        }
2736
2737 1
        if ($obj instanceof PersistentCollection) {
2738 1
            $obj->initialize();
2739
        }
2740 1
    }
2741
2742
    /**
2743
     * Helper method to show an object as string.
2744
     *
2745
     * @param object $obj
2746
     *
2747
     * @return string
2748
     */
2749
    private static function objToStr($obj)
2750
    {
2751
        return method_exists($obj, '__toString') ? (string) $obj : get_class($obj) . '@' . spl_object_id($obj);
2752
    }
2753
2754
    /**
2755
     * Marks an entity as read-only so that it will not be considered for updates during UnitOfWork#commit().
2756
     *
2757
     * This operation cannot be undone as some parts of the UnitOfWork now keep gathering information
2758
     * on this object that might be necessary to perform a correct update.
2759
     *
2760
     * @param object $object
2761
     *
2762
     * @throws ORMInvalidArgumentException
2763
     */
2764 6
    public function markReadOnly($object)
2765
    {
2766 6
        if (! is_object($object) || ! $this->isInIdentityMap($object)) {
2767 1
            throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
2768
        }
2769
2770 5
        $this->readOnlyObjects[spl_object_id($object)] = true;
2771 5
    }
2772
2773
    /**
2774
     * Is this entity read only?
2775
     *
2776
     * @param object $object
2777
     *
2778
     * @return bool
2779
     *
2780
     * @throws ORMInvalidArgumentException
2781
     */
2782 3
    public function isReadOnly($object)
2783
    {
2784 3
        if (! is_object($object)) {
2785
            throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
2786
        }
2787
2788 3
        return isset($this->readOnlyObjects[spl_object_id($object)]);
2789
    }
2790
2791
    /**
2792
     * Perform whatever processing is encapsulated here after completion of the transaction.
2793
     */
2794 1006
    private function afterTransactionComplete()
2795
    {
2796
        $this->performCallbackOnCachedPersister(static function (CachedPersister $persister) {
2797 95
            $persister->afterTransactionComplete();
2798 1006
        });
2799 1006
    }
2800
2801
    /**
2802
     * Perform whatever processing is encapsulated here after completion of the rolled-back.
2803
     */
2804 10
    private function afterTransactionRolledBack()
2805
    {
2806
        $this->performCallbackOnCachedPersister(static function (CachedPersister $persister) {
2807
            $persister->afterTransactionRolledBack();
2808 10
        });
2809 10
    }
2810
2811
    /**
2812
     * Performs an action after the transaction.
2813
     */
2814 1011
    private function performCallbackOnCachedPersister(callable $callback)
2815
    {
2816 1011
        if (! $this->hasCache) {
2817 916
            return;
2818
        }
2819
2820 95
        foreach (array_merge($this->entityPersisters, $this->collectionPersisters) as $persister) {
2821 95
            if ($persister instanceof CachedPersister) {
2822 95
                $callback($persister);
2823
            }
2824
        }
2825 95
    }
2826
2827 1016
    private function dispatchOnFlushEvent()
2828
    {
2829 1016
        if ($this->eventManager->hasListeners(Events::onFlush)) {
2830 4
            $this->eventManager->dispatchEvent(Events::onFlush, new OnFlushEventArgs($this->em));
2831
        }
2832 1016
    }
2833
2834 1011
    private function dispatchPostFlushEvent()
2835
    {
2836 1011
        if ($this->eventManager->hasListeners(Events::postFlush)) {
2837 5
            $this->eventManager->dispatchEvent(Events::postFlush, new PostFlushEventArgs($this->em));
2838
        }
2839 1010
    }
2840
2841
    /**
2842
     * Verifies if two given entities actually are the same based on identifier comparison
2843
     *
2844
     * @param object $entity1
2845
     * @param object $entity2
2846
     *
2847
     * @return bool
2848
     */
2849 17
    private function isIdentifierEquals($entity1, $entity2)
2850
    {
2851 17
        if ($entity1 === $entity2) {
2852
            return true;
2853
        }
2854
2855 17
        $class     = $this->em->getClassMetadata(get_class($entity1));
2856 17
        $persister = $this->getEntityPersister($class->getClassName());
2857
2858 17
        if ($class !== $this->em->getClassMetadata(get_class($entity2))) {
2859 11
            return false;
2860
        }
2861
2862 6
        $identifierFlattener = $this->em->getIdentifierFlattener();
2863
2864 6
        $oid1 = spl_object_id($entity1);
2865 6
        $oid2 = spl_object_id($entity2);
2866
2867 6
        $id1 = $this->entityIdentifiers[$oid1]
2868 6
            ?? $identifierFlattener->flattenIdentifier($class, $persister->getIdentifier($entity1));
2869 6
        $id2 = $this->entityIdentifiers[$oid2]
2870 6
            ?? $identifierFlattener->flattenIdentifier($class, $persister->getIdentifier($entity2));
2871
2872 6
        return $id1 === $id2 || implode(' ', $id1) === implode(' ', $id2);
2873
    }
2874
2875
    /**
2876
     * @throws ORMInvalidArgumentException
2877
     */
2878 1013
    private function assertThatThereAreNoUnintentionallyNonPersistedAssociations() : void
2879
    {
2880 1013
        $entitiesNeedingCascadePersist = array_diff_key($this->nonCascadedNewDetectedEntities, $this->entityInsertions);
2881
2882 1013
        $this->nonCascadedNewDetectedEntities = [];
2883
2884 1013
        if ($entitiesNeedingCascadePersist) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $entitiesNeedingCascadePersist of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
2885 4
            throw ORMInvalidArgumentException::newEntitiesFoundThroughRelationships(
2886 4
                array_values($entitiesNeedingCascadePersist)
2887
            );
2888
        }
2889 1011
    }
2890
2891
    /**
2892
     * This method called by hydrators, and indicates that hydrator totally completed current hydration cycle.
2893
     * Unit of work able to fire deferred events, related to loading events here.
2894
     *
2895
     * @internal should be called internally from object hydrators
2896
     */
2897 878
    public function hydrationComplete()
2898
    {
2899 878
        $this->hydrationCompleteHandler->hydrationComplete();
2900 878
    }
2901
}
2902