Failed Conditions
Pull Request — master (#7448)
by Ilya
09:52
created

UnitOfWork::getScheduledEntityDeletions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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

561
        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...
562 1019
            $value = $property->getValue($entity);
563
564 1019
            if ($property instanceof ToManyAssociationMetadata && $value !== null) {
565 773
                if ($value instanceof PersistentCollection && $value->getOwner() === $entity) {
566 186
                    continue;
567
                }
568
569 770
                $value = $property->wrap($entity, $value, $this->em);
570
571 770
                $property->setValue($entity, $value);
572
573 770
                $actualData[$name] = $value;
574
575 770
                continue;
576
            }
577
578 1019
            if (( ! $class->isIdentifier($name)
579 1019
                    || ! $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

579
                    || ! $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...
580 1019
                    || ! $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

580
                    || ! $class->getProperty($name)->/** @scrutinizer ignore-call */ hasValueGenerator()
Loading history...
581 1019
                    || $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

581
                    || $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...
582 1019
                ) && (! $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

582
                ) && (! $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...
583 1019
                $actualData[$name] = $value;
584
            }
585
        }
586
587 1019
        if (! isset($this->originalEntityData[$oid])) {
588
            // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
589
            // These result in an INSERT.
590 1015
            $this->originalEntityData[$oid] = $actualData;
591 1015
            $changeSet                      = [];
592
593 1015
            foreach ($actualData as $propName => $actualValue) {
594 994
                $property = $class->getProperty($propName);
595
596 994
                if (($property instanceof FieldMetadata) ||
597 994
                    ($property instanceof ToOneAssociationMetadata && $property->isOwningSide())) {
598 994
                    $changeSet[$propName] = [null, $actualValue];
599
                }
600
            }
601
602 1015
            $this->entityChangeSets[$oid] = $changeSet;
603
        } else {
604
            // Entity is "fully" MANAGED: it was already fully persisted before
605
            // and we have a copy of the original data
606 256
            $originalData           = $this->originalEntityData[$oid];
607 256
            $isChangeTrackingNotify = $class->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY;
608 256
            $changeSet              = $isChangeTrackingNotify && isset($this->entityChangeSets[$oid])
609
                ? $this->entityChangeSets[$oid]
610 256
                : [];
611
612 256
            foreach ($actualData as $propName => $actualValue) {
613
                // skip field, its a partially omitted one!
614 245
                if (! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
615 40
                    continue;
616
                }
617
618 245
                $orgValue = $originalData[$propName];
619
620
                // skip if value haven't changed
621 245
                if ($orgValue === $actualValue) {
622 228
                    continue;
623
                }
624
625 109
                $property = $class->getProperty($propName);
626
627
                // Persistent collection was exchanged with the "originally"
628
                // created one. This can only mean it was cloned and replaced
629
                // on another entity.
630 109
                if ($actualValue instanceof PersistentCollection) {
631 8
                    $owner = $actualValue->getOwner();
632
633 8
                    if ($owner === null) { // cloned
634
                        $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

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

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

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

1127
                $calc->addDependency($targetClass->getClassName(), $class->getClassName(), /** @scrutinizer ignore-type */ $weight);
Loading history...
1128
1129
                // If the target class has mapped subclasses, these share the same dependency.
1130 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

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

1271
        $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...
1272
1273 1
        return isset($this->scheduledForSynchronization[$rootEntityName][spl_object_id($entity)]);
1274
    }
1275
1276
    /**
1277
     * INTERNAL:
1278
     * Schedules an entity for deletion.
1279
     *
1280
     * @param object $entity
1281
     */
1282 63
    public function scheduleForDelete($entity)
1283
    {
1284 63
        $oid = spl_object_id($entity);
1285
1286 63
        if (isset($this->entityInsertions[$oid])) {
1287 1
            if ($this->isInIdentityMap($entity)) {
1288
                $this->removeFromIdentityMap($entity);
1289
            }
1290
1291 1
            unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
1292
1293 1
            return; // entity has not been persisted yet, so nothing more to do.
1294
        }
1295
1296 63
        if (! $this->isInIdentityMap($entity)) {
1297 1
            return;
1298
        }
1299
1300 62
        $this->removeFromIdentityMap($entity);
1301
1302 62
        unset($this->entityUpdates[$oid]);
1303
1304 62
        if (! isset($this->entityDeletions[$oid])) {
1305 62
            $this->entityDeletions[$oid] = $entity;
1306 62
            $this->entityStates[$oid]    = self::STATE_REMOVED;
1307
        }
1308 62
    }
1309
1310
    /**
1311
     * Checks whether an entity is registered as removed/deleted with the unit
1312
     * of work.
1313
     *
1314
     * @param object $entity
1315
     *
1316
     * @return bool
1317
     */
1318 13
    public function isScheduledForDelete($entity)
1319
    {
1320 13
        return isset($this->entityDeletions[spl_object_id($entity)]);
1321
    }
1322
1323
    /**
1324
     * Checks whether an entity is scheduled for insertion, update or deletion.
1325
     *
1326
     * @param object $entity
1327
     *
1328
     * @return bool
1329
     */
1330
    public function isEntityScheduled($entity)
1331
    {
1332
        $oid = spl_object_id($entity);
1333
1334
        return isset($this->entityInsertions[$oid])
1335
            || isset($this->entityUpdates[$oid])
1336
            || isset($this->entityDeletions[$oid]);
1337
    }
1338
1339
    /**
1340
     * INTERNAL:
1341
     * Registers an entity in the identity map.
1342
     * Note that entities in a hierarchy are registered with the class name of
1343
     * the root entity.
1344
     *
1345
     * @param object $entity The entity to register.
1346
     *
1347
     * @return bool  TRUE if the registration was successful, FALSE if the identity of
1348
     *               the entity in question is already managed.
1349
     *
1350
     * @throws ORMInvalidArgumentException
1351
     *
1352
     * @ignore
1353
     */
1354 1099
    public function addToIdentityMap($entity)
1355
    {
1356 1099
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1357 1099
        $identifier    = $this->entityIdentifiers[spl_object_id($entity)];
1358
1359 1099
        if (empty($identifier) || in_array(null, $identifier, true)) {
1360 6
            throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->getClassName(), $entity);
1361
        }
1362
1363 1093
        $idHash    = implode(' ', $identifier);
1364 1093
        $className = $classMetadata->getRootClassName();
1365
1366 1093
        if (isset($this->identityMap[$className][$idHash])) {
1367 31
            return false;
1368
        }
1369
1370 1093
        $this->identityMap[$className][$idHash] = $entity;
1371
1372 1093
        return true;
1373
    }
1374
1375
    /**
1376
     * Gets the state of an entity with regard to the current unit of work.
1377
     *
1378
     * @param object   $entity
1379
     * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
1380
     *                         This parameter can be set to improve performance of entity state detection
1381
     *                         by potentially avoiding a database lookup if the distinction between NEW and DETACHED
1382
     *                         is either known or does not matter for the caller of the method.
1383
     *
1384
     * @return int The entity state.
1385
     */
1386 1039
    public function getEntityState($entity, $assume = null)
1387
    {
1388 1039
        $oid = spl_object_id($entity);
1389
1390 1039
        if (isset($this->entityStates[$oid])) {
1391 750
            return $this->entityStates[$oid];
1392
        }
1393
1394 1034
        if ($assume !== null) {
1395 1031
            return $assume;
1396
        }
1397
1398
        // State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
1399
        // Note that you can not remember the NEW or DETACHED state in _entityStates since
1400
        // the UoW does not hold references to such objects and the object hash can be reused.
1401
        // More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
1402 8
        $class     = $this->em->getClassMetadata(get_class($entity));
1403 8
        $persister = $this->getEntityPersister($class->getClassName());
1404 8
        $id        = $persister->getIdentifier($entity);
1405
1406 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...
1407 3
            return self::STATE_NEW;
1408
        }
1409
1410 6
        $flatId = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $id);
1411
1412 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

1412
        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...
1413 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

1413
            || ! $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...
1414 6
            || ! $class->getProperty($class->getSingleIdentifierFieldName())->hasValueGenerator()
1415
        ) {
1416
            // Check for a version field, if available, to avoid a db lookup.
1417 5
            if ($class->isVersioned()) {
1418 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...
1419
                    ? self::STATE_DETACHED
1420 1
                    : self::STATE_NEW;
1421
            }
1422
1423
            // Last try before db lookup: check the identity map.
1424 4
            if ($this->tryGetById($flatId, $class->getRootClassName())) {
1425 1
                return self::STATE_DETACHED;
1426
            }
1427
1428
            // db lookup
1429 4
            if ($this->getEntityPersister($class->getClassName())->exists($entity)) {
1430
                return self::STATE_DETACHED;
1431
            }
1432
1433 4
            return self::STATE_NEW;
1434
        }
1435
1436 1
        if ($class->isIdentifierComposite()
1437 1
            || ! $class->getProperty($class->getSingleIdentifierFieldName()) instanceof FieldMetadata
1438 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

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

2242
            foreach ($association->/** @scrutinizer ignore-call */ getJoinColumns() as $joinColumn) {
Loading history...
2243
                /** @var JoinColumnMetadata $joinColumn */
2244 462
                $joinColumnName  = $joinColumn->getColumnName();
2245 462
                $joinColumnValue = $data[$joinColumnName] ?? null;
2246 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...
2247
2248 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...
2249
                    // the missing key is part of target's entity primary key
2250 266
                    $associatedId = [];
2251
2252 266
                    continue;
2253
                }
2254
2255 284
                $associatedId[$targetField] = $joinColumnValue;
2256
            }
2257
2258 462
            if (! $associatedId) {
2259
                // Foreign key is NULL
2260 266
                $association->setValue($entity, null);
2261 266
                $this->originalEntityData[$oid][$field] = null;
2262
2263 266
                continue;
2264
            }
2265
2266
            // @todo guilhermeblanco Can we remove the need of this somehow?
2267 284
            if (! isset($hints['fetchMode'][$class->getClassName()][$field])) {
2268 281
                $hints['fetchMode'][$class->getClassName()][$field] = $association->getFetchMode();
2269
            }
2270
2271
            // Foreign key is set
2272
            // Check identity map first
2273
            // FIXME: Can break easily with composite keys if join column values are in
2274
            //        wrong order. The correct order is the one in ClassMetadata#identifier.
2275 284
            $relatedIdHash = implode(' ', $associatedId);
2276
2277
            switch (true) {
2278 284
                case isset($this->identityMap[$targetClass->getRootClassName()][$relatedIdHash]):
2279 168
                    $newValue = $this->identityMap[$targetClass->getRootClassName()][$relatedIdHash];
2280
2281
                    // If this is an uninitialized proxy, we are deferring eager loads,
2282
                    // this association is marked as eager fetch, and its an uninitialized proxy (wtf!)
2283
                    // then we can append this entity for eager loading!
2284 168
                    if (! $targetClass->isIdentifierComposite() &&
2285 168
                        $newValue instanceof GhostObjectInterface &&
2286 168
                        isset($hints[self::HINT_DEFEREAGERLOAD]) &&
2287 168
                        $hints['fetchMode'][$class->getClassName()][$field] === FetchMode::EAGER &&
2288 168
                        ! $newValue->isProxyInitialized()
2289
                    ) {
2290
                        $this->eagerLoadingEntities[$targetClass->getRootClassName()][$relatedIdHash] = current($associatedId);
2291
                    }
2292
2293 168
                    break;
2294
2295 190
                case $targetClass->getSubClasses():
2296
                    // If it might be a subtype, it can not be lazy. There isn't even
2297
                    // a way to solve this with deferred eager loading, which means putting
2298
                    // an entity with subclasses at a *-to-one location is really bad! (performance-wise)
2299 29
                    $persister = $this->getEntityPersister($targetEntity);
2300 29
                    $newValue  = $persister->loadToOneEntity($association, $entity, $associatedId);
2301 29
                    break;
2302
2303
                default:
2304
                    // Proxies do not carry any kind of original entity data until they're fully loaded/initialized
2305 163
                    $managedData = [];
2306
2307 163
                    $normalizedAssociatedId = $this->normalizeIdentifier->__invoke(
2308 163
                        $this->em,
2309 163
                        $targetClass,
2310 163
                        $associatedId
2311
                    );
2312
2313
                    switch (true) {
2314
                        // We are negating the condition here. Other cases will assume it is valid!
2315 163
                        case $hints['fetchMode'][$class->getClassName()][$field] !== FetchMode::EAGER:
2316 156
                            $newValue = $this->em->getProxyFactory()->getProxy($targetClass, $normalizedAssociatedId);
2317 156
                            break;
2318
2319
                        // Deferred eager load only works for single identifier classes
2320 7
                        case isset($hints[self::HINT_DEFEREAGERLOAD]) && ! $targetClass->isIdentifierComposite():
2321
                            // TODO: Is there a faster approach?
2322 7
                            $this->eagerLoadingEntities[$targetClass->getRootClassName()][$relatedIdHash] = current($normalizedAssociatedId);
2323
2324 7
                            $newValue = $this->em->getProxyFactory()->getProxy($targetClass, $normalizedAssociatedId);
2325 7
                            break;
2326
2327
                        default:
2328
                            // TODO: This is very imperformant, ignore it?
2329
                            $newValue = $this->em->find($targetEntity, $normalizedAssociatedId);
2330
                            // Needed to re-assign original entity data for freshly loaded entity
2331
                            $managedData = $this->originalEntityData[spl_object_id($newValue)];
2332
                            break;
2333
                    }
2334
2335
                    // @TODO using `$associatedId` here seems to be risky.
2336 163
                    $this->registerManaged($newValue, $associatedId, $managedData);
2337
2338 163
                    break;
2339
            }
2340
2341 284
            $this->originalEntityData[$oid][$field] = $newValue;
2342 284
            $association->setValue($entity, $newValue);
2343
2344 284
            if ($association->getInversedBy()
2345 284
                && $association instanceof OneToOneAssociationMetadata
2346
                // @TODO refactor this
2347
                // we don't want to set any values in un-initialized proxies
2348
                && ! (
2349 56
                    $newValue instanceof GhostObjectInterface
2350 284
                    && ! $newValue->isProxyInitialized()
2351
                )
2352
            ) {
2353 19
                $inverseAssociation = $targetClass->getProperty($association->getInversedBy());
2354
2355 284
                $inverseAssociation->setValue($newValue, $entity);
2356
            }
2357
        }
2358
2359
        // defer invoking of postLoad event to hydration complete step
2360 660
        $this->hydrationCompleteHandler->deferPostLoadInvoking($class, $entity);
2361
2362 660
        return $entity;
2363
    }
2364
2365 861
    public function triggerEagerLoads()
2366
    {
2367 861
        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...
2368 861
            return;
2369
        }
2370
2371
        // avoid infinite recursion
2372 7
        $eagerLoadingEntities       = $this->eagerLoadingEntities;
2373 7
        $this->eagerLoadingEntities = [];
2374
2375 7
        foreach ($eagerLoadingEntities as $entityName => $ids) {
2376 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...
2377
                continue;
2378
            }
2379
2380 7
            $class = $this->em->getClassMetadata($entityName);
2381
2382 7
            $this->getEntityPersister($entityName)->loadAll(
2383 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...
2384
            );
2385
        }
2386 7
    }
2387
2388
    /**
2389
     * Initializes (loads) an uninitialized persistent collection of an entity.
2390
     *
2391
     * @param PersistentCollection $collection The collection to initialize.
2392
     *
2393
     * @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733.
2394
     */
2395 139
    public function loadCollection(PersistentCollection $collection)
2396
    {
2397 139
        $association = $collection->getMapping();
2398 139
        $persister   = $this->getEntityPersister($association->getTargetEntity());
2399
2400 139
        if ($association instanceof OneToManyAssociationMetadata) {
2401 74
            $persister->loadOneToManyCollection($association, $collection->getOwner(), $collection);
2402
        } else {
2403 75
            $persister->loadManyToManyCollection($association, $collection->getOwner(), $collection);
2404
        }
2405
2406 139
        $collection->setInitialized(true);
2407 139
    }
2408
2409
    /**
2410
     * Gets the identity map of the UnitOfWork.
2411
     *
2412
     * @return object[]
2413
     */
2414 1
    public function getIdentityMap()
2415
    {
2416 1
        return $this->identityMap;
2417
    }
2418
2419
    /**
2420
     * Gets the original data of an entity. The original data is the data that was
2421
     * present at the time the entity was reconstituted from the database.
2422
     *
2423
     * @param object $entity
2424
     *
2425
     * @return mixed[]
2426
     */
2427 121
    public function getOriginalEntityData($entity)
2428
    {
2429 121
        $oid = spl_object_id($entity);
2430
2431 121
        return $this->originalEntityData[$oid] ?? [];
2432
    }
2433
2434
    /**
2435
     * @param object  $entity
2436
     * @param mixed[] $data
2437
     *
2438
     * @ignore
2439
     */
2440
    public function setOriginalEntityData($entity, array $data)
2441
    {
2442
        $this->originalEntityData[spl_object_id($entity)] = $data;
2443
    }
2444
2445
    /**
2446
     * INTERNAL:
2447
     * Sets a property value of the original data array of an entity.
2448
     *
2449
     * @param string $oid
2450
     * @param string $property
2451
     * @param mixed  $value
2452
     *
2453
     * @ignore
2454
     */
2455 301
    public function setOriginalEntityProperty($oid, $property, $value)
2456
    {
2457 301
        $this->originalEntityData[$oid][$property] = $value;
2458 301
    }
2459
2460
    /**
2461
     * Gets the identifier of an entity.
2462
     * The returned value is always an array of identifier values. If the entity
2463
     * has a composite identifier then the identifier values are in the same
2464
     * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
2465
     *
2466
     * @param object $entity
2467
     *
2468
     * @return mixed[] The identifier values.
2469
     */
2470 568
    public function getEntityIdentifier($entity)
2471
    {
2472 568
        return $this->entityIdentifiers[spl_object_id($entity)];
2473
    }
2474
2475
    /**
2476
     * Processes an entity instance to extract their identifier values.
2477
     *
2478
     * @param object $entity The entity instance.
2479
     *
2480
     * @return mixed A scalar value.
2481
     *
2482
     * @throws ORMInvalidArgumentException
2483
     */
2484 70
    public function getSingleIdentifierValue($entity)
2485
    {
2486 70
        $class     = $this->em->getClassMetadata(get_class($entity));
2487 70
        $persister = $this->getEntityPersister($class->getClassName());
2488
2489 70
        if ($class->isIdentifierComposite()) {
2490
            throw ORMInvalidArgumentException::invalidCompositeIdentifier();
2491
        }
2492
2493 70
        $values = $this->isInIdentityMap($entity)
2494 58
            ? $this->getEntityIdentifier($entity)
2495 70
            : $persister->getIdentifier($entity);
2496
2497 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...
2498
    }
2499
2500
    /**
2501
     * Tries to find an entity with the given identifier in the identity map of
2502
     * this UnitOfWork.
2503
     *
2504
     * @param mixed|mixed[] $id            The entity identifier to look for.
2505
     * @param string        $rootClassName The name of the root class of the mapped entity hierarchy.
2506
     *
2507
     * @return object|bool Returns the entity with the specified identifier if it exists in
2508
     *                     this UnitOfWork, FALSE otherwise.
2509
     */
2510 537
    public function tryGetById($id, $rootClassName)
2511
    {
2512 537
        $idHash = implode(' ', (array) $id);
2513
2514 537
        return $this->identityMap[$rootClassName][$idHash] ?? false;
2515
    }
2516
2517
    /**
2518
     * Schedules an entity for dirty-checking at commit-time.
2519
     *
2520
     * @param object $entity The entity to schedule for dirty-checking.
2521
     */
2522 5
    public function scheduleForSynchronization($entity)
2523
    {
2524 5
        $rootClassName = $this->em->getClassMetadata(get_class($entity))->getRootClassName();
2525
2526 5
        $this->scheduledForSynchronization[$rootClassName][spl_object_id($entity)] = $entity;
2527 5
    }
2528
2529
    /**
2530
     * Checks whether the UnitOfWork has any pending insertions.
2531
     *
2532
     * @return bool TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
2533
     */
2534
    public function hasPendingInsertions()
2535
    {
2536
        return ! empty($this->entityInsertions);
2537
    }
2538
2539
    /**
2540
     * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
2541
     * number of entities in the identity map.
2542
     *
2543
     * @return int
2544
     */
2545 1
    public function size()
2546
    {
2547 1
        return array_sum(array_map('count', $this->identityMap));
2548
    }
2549
2550
    /**
2551
     * Gets the EntityPersister for an Entity.
2552
     *
2553
     * @param string $entityName The name of the Entity.
2554
     *
2555
     * @return EntityPersister
2556
     */
2557 1085
    public function getEntityPersister($entityName)
2558
    {
2559 1085
        if (isset($this->entityPersisters[$entityName])) {
2560 1031
            return $this->entityPersisters[$entityName];
2561
        }
2562
2563 1085
        $class = $this->em->getClassMetadata($entityName);
2564
2565
        switch (true) {
2566 1085
            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...
2567 1042
                $persister = new BasicEntityPersister($this->em, $class);
2568 1042
                break;
2569
2570 385
            case $class->inheritanceType === InheritanceType::SINGLE_TABLE:
2571 223
                $persister = new SingleTablePersister($this->em, $class);
2572 223
                break;
2573
2574 355
            case $class->inheritanceType === InheritanceType::JOINED:
2575 355
                $persister = new JoinedSubclassPersister($this->em, $class);
2576 355
                break;
2577
2578
            default:
2579
                throw new RuntimeException('No persister found for entity.');
2580
        }
2581
2582 1085
        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

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