Failed Conditions
Pull Request — master (#7448)
by Ilya
10:20
created

UnitOfWork::scheduleExtraUpdate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 2
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 2276
    public function __construct(EntityManagerInterface $em)
313
    {
314 2276
        $this->em                       = $em;
315 2276
        $this->eventManager             = $em->getEventManager();
316 2276
        $this->listenersInvoker         = new ListenersInvoker($em);
317 2276
        $this->hasCache                 = $em->getConfiguration()->isSecondLevelCacheEnabled();
318 2276
        $this->instantiator             = new Instantiator();
319 2276
        $this->hydrationCompleteHandler = new HydrationCompleteHandler($this->listenersInvoker, $em);
320 2276
        $this->normalizeIdentifier      = new NormalizeIdentifier();
321 2276
    }
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 1022
    public function commit()
340
    {
341 1022
        if ($this->commitInProgress) {
342 1
            throw CommitInsideCommit::create();
343
        }
344
345 1022
        $this->commitInProgress = true;
346
347
        try {
348 1022
            $this->doCommit();
349 1011
        } finally {
350 1022
            $this->commitInProgress = false;
351
        }
352 1011
    }
353
354 1022
    private function doCommit()
355
    {
356
        // Raise preFlush
357 1022
        if ($this->eventManager->hasListeners(Events::preFlush)) {
358 4
            $this->eventManager->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em));
359
        }
360
361 1021
        $this->computeChangeSets();
362
363 1019
        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 159
                $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 124
                $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 38
                $this->collectionUpdates ||
367 35
                $this->collectionDeletions ||
368 1019
                $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 23
            $this->dispatchOnFlushEvent();
370 23
            $this->dispatchPostFlushEvent();
371
372 23
            $this->postCommitCleanup();
373
374 23
            return; // Nothing to do.
375
        }
376
377 1013
        $this->assertThatThereAreNoUnintentionallyNonPersistedAssociations();
378
379 1011
        if ($this->orphanRemovals) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->orphanRemovals of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
380 15
            foreach ($this->orphanRemovals as $orphan) {
381 15
                $this->remove($orphan);
382
            }
383
        }
384
385 1011
        $this->dispatchOnFlushEvent();
386
387
        // Now we need a commit order to maintain referential integrity
388 1011
        $commitOrder = $this->getCommitOrder();
389
390 1011
        $conn = $this->em->getConnection();
391 1011
        $conn->beginTransaction();
392
393
        try {
394
            // Collection deletions (deletions of complete collections)
395 1011
            foreach ($this->collectionDeletions as $collectionToDelete) {
396 19
                $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
397
            }
398
399 1011
            if ($this->entityInsertions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityInsertions of type array<mixed,object> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

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

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

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

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

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

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

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

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

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

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

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

567
        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...
568 1021
            $value = $property->getValue($entity);
569
570 1021
            if ($property instanceof ToManyAssociationMetadata && $value !== null) {
571 773
                if ($value instanceof PersistentCollection && $value->getOwner() === $entity) {
572 186
                    continue;
573
                }
574
575 770
                $value = $property->wrap($entity, $value, $this->em);
576
577 770
                $property->setValue($entity, $value);
578
579 770
                $actualData[$name] = $value;
580
581 770
                continue;
582
            }
583
584 1021
            if (( ! $class->isIdentifier($name)
585 1021
                    || ! $class->getProperty($name) instanceof FieldMetadata
0 ignored issues
show
Bug introduced by
The method getProperty() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

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

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

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

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

587
                    || $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...
588 1021
                ) && (! $class->isVersioned() || $name !== $class->versionProperty->getName())) {
0 ignored issues
show
Bug introduced by
The method isVersioned() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

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

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

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

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

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

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

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

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

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

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

1418
        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...
1419 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

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

1444
            || ! $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...
1445
            // if we have a pre insert generator we can't be sure that having an id
1446
            // really means that the entity exists. We have to verify this through
1447
            // the last resort: a db lookup
1448
1449
            // Last try before db lookup: check the identity map.
1450
            if ($this->tryGetById($flatId, $class->getRootClassName())) {
1451
                return self::STATE_DETACHED;
1452
            }
1453
1454
            // db lookup
1455
            if ($this->getEntityPersister($class->getClassName())->exists($entity)) {
1456
                return self::STATE_DETACHED;
1457
            }
1458
1459
            return self::STATE_NEW;
1460
        }
1461
1462 1
        return self::STATE_DETACHED;
1463
    }
1464
1465
    /**
1466
     * INTERNAL:
1467
     * Removes an entity from the identity map. This effectively detaches the
1468
     * entity from the persistence management of Doctrine.
1469
     *
1470
     * @param object $entity
1471
     *
1472
     * @return bool
1473
     *
1474
     * @throws ORMInvalidArgumentException
1475
     *
1476
     * @ignore
1477
     */
1478 62
    public function removeFromIdentityMap($entity)
1479
    {
1480 62
        $oid           = spl_object_id($entity);
1481 62
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1482 62
        $idHash        = implode(' ', $this->entityIdentifiers[$oid]);
1483
1484 62
        if ($idHash === '') {
1485
            throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'remove from identity map');
1486
        }
1487
1488 62
        $className = $classMetadata->getRootClassName();
1489
1490 62
        if (isset($this->identityMap[$className][$idHash])) {
1491 62
            unset($this->identityMap[$className][$idHash], $this->readOnlyObjects[$oid]);
1492
1493 62
            return true;
1494
        }
1495
1496
        return false;
1497
    }
1498
1499
    /**
1500
     * INTERNAL:
1501
     * Gets an entity in the identity map by its identifier hash.
1502
     *
1503
     * @param string $idHash
1504
     * @param string $rootClassName
1505
     *
1506
     * @return object
1507
     *
1508
     * @ignore
1509
     */
1510 6
    public function getByIdHash($idHash, $rootClassName)
1511
    {
1512 6
        return $this->identityMap[$rootClassName][$idHash];
1513
    }
1514
1515
    /**
1516
     * INTERNAL:
1517
     * Tries to get an entity by its identifier hash. If no entity is found for
1518
     * the given hash, FALSE is returned.
1519
     *
1520
     * @param mixed  $idHash        (must be possible to cast it to string)
1521
     * @param string $rootClassName
1522
     *
1523
     * @return object|bool The found entity or FALSE.
1524
     *
1525
     * @ignore
1526
     */
1527
    public function tryGetByIdHash($idHash, $rootClassName)
1528
    {
1529
        $stringIdHash = (string) $idHash;
1530
1531
        return $this->identityMap[$rootClassName][$stringIdHash] ?? false;
1532
    }
1533
1534
    /**
1535
     * Checks whether an entity is registered in the identity map of this UnitOfWork.
1536
     *
1537
     * @param object $entity
1538
     *
1539
     * @return bool
1540
     */
1541 147
    public function isInIdentityMap($entity)
1542
    {
1543 147
        $oid = spl_object_id($entity);
1544
1545 147
        if (empty($this->entityIdentifiers[$oid])) {
1546 23
            return false;
1547
        }
1548
1549 133
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1550 133
        $idHash        = implode(' ', $this->entityIdentifiers[$oid]);
1551
1552 133
        return isset($this->identityMap[$classMetadata->getRootClassName()][$idHash]);
1553
    }
1554
1555
    /**
1556
     * INTERNAL:
1557
     * Checks whether an identifier hash exists in the identity map.
1558
     *
1559
     * @param string $idHash
1560
     * @param string $rootClassName
1561
     *
1562
     * @return bool
1563
     *
1564
     * @ignore
1565
     */
1566
    public function containsIdHash($idHash, $rootClassName)
1567
    {
1568
        return isset($this->identityMap[$rootClassName][$idHash]);
1569
    }
1570
1571
    /**
1572
     * Persists an entity as part of the current unit of work.
1573
     *
1574
     * @param object $entity The entity to persist.
1575
     */
1576 1033
    public function persist($entity)
1577
    {
1578 1033
        $visited = [];
1579
1580 1033
        $this->doPersist($entity, $visited);
1581 1026
    }
1582
1583
    /**
1584
     * Persists an entity as part of the current unit of work.
1585
     *
1586
     * This method is internally called during persist() cascades as it tracks
1587
     * the already visited entities to prevent infinite recursions.
1588
     *
1589
     * @param object   $entity  The entity to persist.
1590
     * @param object[] $visited The already visited entities.
1591
     *
1592
     * @throws ORMInvalidArgumentException
1593
     * @throws UnexpectedValueException
1594
     */
1595 1033
    private function doPersist($entity, array &$visited)
1596
    {
1597 1033
        $oid = spl_object_id($entity);
1598
1599 1033
        if (isset($visited[$oid])) {
1600 109
            return; // Prevent infinite recursion
1601
        }
1602
1603 1033
        $visited[$oid] = $entity; // Mark visited
1604
1605 1033
        $class = $this->em->getClassMetadata(get_class($entity));
1606
1607
        // We assume NEW, so DETACHED entities result in an exception on flush (constraint violation).
1608
        // If we would detect DETACHED here we would throw an exception anyway with the same
1609
        // consequences (not recoverable/programming error), so just assuming NEW here
1610
        // lets us avoid some database lookups for entities with natural identifiers.
1611 1033
        $entityState = $this->getEntityState($entity, self::STATE_NEW);
1612
1613
        switch ($entityState) {
1614 1033
            case self::STATE_MANAGED:
1615
                // Nothing to do, except if policy is "deferred explicit"
1616 220
                if ($class->changeTrackingPolicy === ChangeTrackingPolicy::DEFERRED_EXPLICIT) {
0 ignored issues
show
Bug introduced by
Accessing changeTrackingPolicy on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1617 3
                    $this->scheduleForSynchronization($entity);
1618
                }
1619 220
                break;
1620
1621 1033
            case self::STATE_NEW:
1622 1032
                $this->persistNew($class, $entity);
1623 1032
                break;
1624
1625 1
            case self::STATE_REMOVED:
1626
                // Entity becomes managed again
1627 1
                unset($this->entityDeletions[$oid]);
1628 1
                $this->addToIdentityMap($entity);
1629
1630 1
                $this->entityStates[$oid] = self::STATE_MANAGED;
1631 1
                break;
1632
1633
            case self::STATE_DETACHED:
1634
                // Can actually not happen right now since we assume STATE_NEW.
1635
                throw ORMInvalidArgumentException::detachedEntityCannot($entity, 'persisted');
1636
1637
            default:
1638
                throw new UnexpectedValueException(
1639
                    sprintf('Unexpected entity state: %d.%s', $entityState, self::objToStr($entity))
1640
                );
1641
        }
1642
1643 1033
        $this->cascadePersist($entity, $visited);
1644 1026
    }
1645
1646
    /**
1647
     * Deletes an entity as part of the current unit of work.
1648
     *
1649
     * @param object $entity The entity to remove.
1650
     */
1651 62
    public function remove($entity)
1652
    {
1653 62
        $visited = [];
1654
1655 62
        $this->doRemove($entity, $visited);
1656 62
    }
1657
1658
    /**
1659
     * Deletes an entity as part of the current unit of work.
1660
     *
1661
     * This method is internally called during delete() cascades as it tracks
1662
     * the already visited entities to prevent infinite recursions.
1663
     *
1664
     * @param object   $entity  The entity to delete.
1665
     * @param object[] $visited The map of the already visited entities.
1666
     *
1667
     * @throws ORMInvalidArgumentException If the instance is a detached entity.
1668
     * @throws UnexpectedValueException
1669
     */
1670 62
    private function doRemove($entity, array &$visited)
1671
    {
1672 62
        $oid = spl_object_id($entity);
1673
1674 62
        if (isset($visited[$oid])) {
1675 1
            return; // Prevent infinite recursion
1676
        }
1677
1678 62
        $visited[$oid] = $entity; // mark visited
1679
1680
        // Cascade first, because scheduleForDelete() removes the entity from the identity map, which
1681
        // can cause problems when a lazy proxy has to be initialized for the cascade operation.
1682 62
        $this->cascadeRemove($entity, $visited);
1683
1684 62
        $class       = $this->em->getClassMetadata(get_class($entity));
1685 62
        $entityState = $this->getEntityState($entity);
1686
1687
        switch ($entityState) {
1688 62
            case self::STATE_NEW:
1689 62
            case self::STATE_REMOVED:
1690
                // nothing to do
1691 2
                break;
1692
1693 62
            case self::STATE_MANAGED:
1694 62
                $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preRemove);
1695
1696 62
                if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1697 8
                    $this->listenersInvoker->invoke($class, Events::preRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
1698
                }
1699
1700 62
                $this->scheduleForDelete($entity);
1701 62
                break;
1702
1703
            case self::STATE_DETACHED:
1704
                throw ORMInvalidArgumentException::detachedEntityCannot($entity, 'removed');
1705
            default:
1706
                throw new UnexpectedValueException(
1707
                    sprintf('Unexpected entity state: %d.%s', $entityState, self::objToStr($entity))
1708
                );
1709
        }
1710 62
    }
1711
1712
    /**
1713
     * Refreshes the state of the given entity from the database, overwriting
1714
     * any local, unpersisted changes.
1715
     *
1716
     * @param object $entity The entity to refresh.
1717
     *
1718
     * @throws InvalidArgumentException If the entity is not MANAGED.
1719
     */
1720 15
    public function refresh($entity)
1721
    {
1722 15
        $visited = [];
1723
1724 15
        $this->doRefresh($entity, $visited);
1725 15
    }
1726
1727
    /**
1728
     * Executes a refresh operation on an entity.
1729
     *
1730
     * @param object   $entity  The entity to refresh.
1731
     * @param object[] $visited The already visited entities during cascades.
1732
     *
1733
     * @throws ORMInvalidArgumentException If the entity is not MANAGED.
1734
     */
1735 15
    private function doRefresh($entity, array &$visited)
1736
    {
1737 15
        $oid = spl_object_id($entity);
1738
1739 15
        if (isset($visited[$oid])) {
1740
            return; // Prevent infinite recursion
1741
        }
1742
1743 15
        $visited[$oid] = $entity; // mark visited
1744
1745 15
        $class = $this->em->getClassMetadata(get_class($entity));
1746
1747 15
        if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
1748
            throw ORMInvalidArgumentException::entityNotManaged($entity);
1749
        }
1750
1751 15
        $this->getEntityPersister($class->getClassName())->refresh(
1752 15
            array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
0 ignored issues
show
Bug introduced by
It seems like array_combine($class->ge...ntityIdentifiers[$oid]) can also be of type false; however, parameter $id of Doctrine\ORM\Persisters\...ityPersister::refresh() does only seem to accept array, 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

1752
            /** @scrutinizer ignore-type */ array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
Loading history...
1753 15
            $entity
1754
        );
1755
1756 15
        $this->cascadeRefresh($entity, $visited);
1757 15
    }
1758
1759
    /**
1760
     * Cascades a refresh operation to associated entities.
1761
     *
1762
     * @param object   $entity
1763
     * @param object[] $visited
1764
     */
1765 15
    private function cascadeRefresh($entity, array &$visited)
1766
    {
1767 15
        $class = $this->em->getClassMetadata(get_class($entity));
1768
1769 15
        foreach ($class->getDeclaredPropertiesIterator() as $association) {
1770 15
            if (! ($association instanceof AssociationMetadata && in_array('refresh', $association->getCascade(), true))) {
1771 15
                continue;
1772
            }
1773
1774 4
            $relatedEntities = $association->getValue($entity);
1775
1776
            switch (true) {
1777 4
                case $relatedEntities instanceof PersistentCollection:
1778
                    // Unwrap so that foreach() does not initialize
1779 4
                    $relatedEntities = $relatedEntities->unwrap();
1780
                    // break; is commented intentionally!
1781
1782
                case $relatedEntities instanceof Collection:
1783
                case is_array($relatedEntities):
1784 4
                    foreach ($relatedEntities as $relatedEntity) {
1785
                        $this->doRefresh($relatedEntity, $visited);
1786
                    }
1787 4
                    break;
1788
1789
                case $relatedEntities !== null:
1790
                    $this->doRefresh($relatedEntities, $visited);
1791
                    break;
1792
1793
                default:
1794
                    // Do nothing
1795
            }
1796
        }
1797 15
    }
1798
1799
    /**
1800
     * Cascades the save operation to associated entities.
1801
     *
1802
     * @param object   $entity
1803
     * @param object[] $visited
1804
     *
1805
     * @throws ORMInvalidArgumentException
1806
     */
1807 1033
    private function cascadePersist($entity, array &$visited)
1808
    {
1809 1033
        $class = $this->em->getClassMetadata(get_class($entity));
1810
1811 1033
        if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
1812
            // nothing to do - proxy is not initialized, therefore we don't do anything with it
1813 1
            return;
1814
        }
1815
1816 1033
        foreach ($class->getDeclaredPropertiesIterator() as $association) {
1817 1033
            if (! ($association instanceof AssociationMetadata && in_array('persist', $association->getCascade(), true))) {
1818 1033
                continue;
1819
            }
1820
1821
            /** @var AssociationMetadata $association */
1822 647
            $relatedEntities = $association->getValue($entity);
1823 647
            $targetEntity    = $association->getTargetEntity();
1824
1825
            switch (true) {
1826 647
                case $relatedEntities instanceof PersistentCollection:
1827
                    // Unwrap so that foreach() does not initialize
1828 13
                    $relatedEntities = $relatedEntities->unwrap();
1829
                    // break; is commented intentionally!
1830
1831 647
                case $relatedEntities instanceof Collection:
1832 584
                case is_array($relatedEntities):
1833 542
                    if (! ($association instanceof ToManyAssociationMetadata)) {
1834 3
                        throw ORMInvalidArgumentException::invalidAssociation(
1835 3
                            $this->em->getClassMetadata($targetEntity),
1836 3
                            $association,
1837 3
                            $relatedEntities
1838
                        );
1839
                    }
1840
1841 539
                    foreach ($relatedEntities as $relatedEntity) {
1842 283
                        $this->doPersist($relatedEntity, $visited);
1843
                    }
1844
1845 539
                    break;
1846
1847 573
                case $relatedEntities !== null:
1848 241
                    if (! $relatedEntities instanceof $targetEntity) {
1849 4
                        throw ORMInvalidArgumentException::invalidAssociation(
1850 4
                            $this->em->getClassMetadata($targetEntity),
1851 4
                            $association,
1852 4
                            $relatedEntities
1853
                        );
1854
                    }
1855
1856 237
                    $this->doPersist($relatedEntities, $visited);
1857 237
                    break;
1858
1859
                default:
1860
                    // Do nothing
1861
            }
1862
        }
1863 1026
    }
1864
1865
    /**
1866
     * Cascades the delete operation to associated entities.
1867
     *
1868
     * @param object   $entity
1869
     * @param object[] $visited
1870
     */
1871 62
    private function cascadeRemove($entity, array &$visited)
1872
    {
1873 62
        $entitiesToCascade = [];
1874 62
        $class             = $this->em->getClassMetadata(get_class($entity));
1875
1876 62
        foreach ($class->getDeclaredPropertiesIterator() as $association) {
1877 62
            if (! ($association instanceof AssociationMetadata && in_array('remove', $association->getCascade(), true))) {
1878 62
                continue;
1879
            }
1880
1881 25
            if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
1882 6
                $entity->initializeProxy();
1883
            }
1884
1885 25
            $relatedEntities = $association->getValue($entity);
1886
1887
            switch (true) {
1888 25
                case $relatedEntities instanceof Collection:
1889 18
                case is_array($relatedEntities):
1890
                    // If its a PersistentCollection initialization is intended! No unwrap!
1891 20
                    foreach ($relatedEntities as $relatedEntity) {
1892 10
                        $entitiesToCascade[] = $relatedEntity;
1893
                    }
1894 20
                    break;
1895
1896 18
                case $relatedEntities !== null:
1897 7
                    $entitiesToCascade[] = $relatedEntities;
1898 7
                    break;
1899
1900
                default:
1901
                    // Do nothing
1902
            }
1903
        }
1904
1905 62
        foreach ($entitiesToCascade as $relatedEntity) {
1906 16
            $this->doRemove($relatedEntity, $visited);
1907
        }
1908 62
    }
1909
1910
    /**
1911
     * Acquire a lock on the given entity.
1912
     *
1913
     * @param object $entity
1914
     * @param int    $lockMode
1915
     * @param int    $lockVersion
1916
     *
1917
     * @throws ORMInvalidArgumentException
1918
     * @throws TransactionRequiredException
1919
     * @throws OptimisticLockException
1920
     * @throws InvalidArgumentException
1921
     */
1922 10
    public function lock($entity, $lockMode, $lockVersion = null)
1923
    {
1924 10
        if ($entity === null) {
1925 1
            throw new InvalidArgumentException('No entity passed to UnitOfWork#lock().');
1926
        }
1927
1928 9
        if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) {
1929 1
            throw ORMInvalidArgumentException::entityNotManaged($entity);
1930
        }
1931
1932 8
        $class = $this->em->getClassMetadata(get_class($entity));
1933
1934
        switch (true) {
1935 8
            case $lockMode === LockMode::OPTIMISTIC:
1936 6
                if (! $class->isVersioned()) {
1937 1
                    throw OptimisticLockException::notVersioned($class->getClassName());
1938
                }
1939
1940 5
                if ($lockVersion === null) {
1941 1
                    return;
1942
                }
1943
1944 4
                if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
1945 1
                    $entity->initializeProxy();
1946
                }
1947
1948 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...
1949
1950 4
                if ($entityVersion !== $lockVersion) {
1951 2
                    throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion);
1952
                }
1953
1954 2
                break;
1955
1956 2
            case $lockMode === LockMode::NONE:
1957 2
            case $lockMode === LockMode::PESSIMISTIC_READ:
1958 1
            case $lockMode === LockMode::PESSIMISTIC_WRITE:
1959 2
                if (! $this->em->getConnection()->isTransactionActive()) {
1960 2
                    throw TransactionRequiredException::transactionRequired();
1961
                }
1962
1963
                $oid = spl_object_id($entity);
1964
1965
                $this->getEntityPersister($class->getClassName())->lock(
1966
                    array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
0 ignored issues
show
Bug introduced by
It seems like array_combine($class->ge...ntityIdentifiers[$oid]) can also be of type false; however, parameter $criteria of Doctrine\ORM\Persisters\...EntityPersister::lock() does only seem to accept array, 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

1966
                    /** @scrutinizer ignore-type */ array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
Loading history...
1967
                    $lockMode
1968
                );
1969
                break;
1970
1971
            default:
1972
                // Do nothing
1973
        }
1974 2
    }
1975
1976
    /**
1977
     * Clears the UnitOfWork.
1978
     */
1979 1219
    public function clear()
1980
    {
1981 1219
        $this->entityPersisters               =
1982 1219
        $this->collectionPersisters           =
1983 1219
        $this->eagerLoadingEntities           =
1984 1219
        $this->identityMap                    =
1985 1219
        $this->entityIdentifiers              =
1986 1219
        $this->originalEntityData             =
1987 1219
        $this->entityChangeSets               =
1988 1219
        $this->entityStates                   =
1989 1219
        $this->scheduledForSynchronization    =
1990 1219
        $this->entityInsertions               =
1991 1219
        $this->entityUpdates                  =
1992 1219
        $this->entityDeletions                =
1993 1219
        $this->collectionDeletions            =
1994 1219
        $this->collectionUpdates              =
1995 1219
        $this->extraUpdates                   =
1996 1219
        $this->readOnlyObjects                =
1997 1219
        $this->visitedCollections             =
1998 1219
        $this->nonCascadedNewDetectedEntities =
1999 1219
        $this->orphanRemovals                 = [];
2000 1219
    }
2001
2002
    /**
2003
     * INTERNAL:
2004
     * Schedules an orphaned entity for removal. The remove() operation will be
2005
     * invoked on that entity at the beginning of the next commit of this
2006
     * UnitOfWork.
2007
     *
2008
     * @param object $entity
2009
     *
2010
     * @ignore
2011
     */
2012 16
    public function scheduleOrphanRemoval($entity)
2013
    {
2014 16
        $this->orphanRemovals[spl_object_id($entity)] = $entity;
2015 16
    }
2016
2017
    /**
2018
     * INTERNAL:
2019
     * Cancels a previously scheduled orphan removal.
2020
     *
2021
     * @param object $entity
2022
     *
2023
     * @ignore
2024
     */
2025 111
    public function cancelOrphanRemoval($entity)
2026
    {
2027 111
        unset($this->orphanRemovals[spl_object_id($entity)]);
2028 111
    }
2029
2030
    /**
2031
     * INTERNAL:
2032
     * Schedules a complete collection for removal when this UnitOfWork commits.
2033
     */
2034 22
    public function scheduleCollectionDeletion(PersistentCollection $coll)
2035
    {
2036 22
        $coid = spl_object_id($coll);
2037
2038
        // TODO: if $coll is already scheduled for recreation ... what to do?
2039
        // Just remove $coll from the scheduled recreations?
2040 22
        unset($this->collectionUpdates[$coid]);
2041
2042 22
        $this->collectionDeletions[$coid] = $coll;
2043 22
    }
2044
2045
    /**
2046
     * @return bool
2047
     */
2048 8
    public function isCollectionScheduledForDeletion(PersistentCollection $coll)
2049
    {
2050 8
        return isset($this->collectionDeletions[spl_object_id($coll)]);
2051
    }
2052
2053
    /**
2054
     * INTERNAL:
2055
     * Creates a new instance of the mapped class, without invoking the constructor.
2056
     * This is only meant to be used internally, and should not be consumed by end users.
2057
     *
2058
     * @return EntityManagerAware|object
2059
     *
2060
     * @ignore
2061
     */
2062 665
    public function newInstance(ClassMetadata $class)
2063
    {
2064 665
        $entity = $this->instantiator->instantiate($class->getClassName());
2065
2066 665
        if ($entity instanceof EntityManagerAware) {
2067 5
            $entity->injectEntityManager($this->em, $class);
2068
        }
2069
2070 665
        return $entity;
2071
    }
2072
2073
    /**
2074
     * INTERNAL:
2075
     * Creates an entity. Used for reconstitution of persistent entities.
2076
     *
2077
     * {@internal Highly performance-sensitive method. }}
2078
     *
2079
     * @param string  $className The name of the entity class.
2080
     * @param mixed[] $data      The data for the entity.
2081
     * @param mixed[] $hints     Any hints to account for during reconstitution/lookup of the entity.
2082
     *
2083
     * @return object The managed entity instance.
2084
     *
2085
     * @ignore
2086
     * @todo Rename: getOrCreateEntity
2087
     */
2088 802
    public function createEntity($className, array $data, &$hints = [])
2089
    {
2090 802
        $class  = $this->em->getClassMetadata($className);
2091 802
        $id     = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $data);
2092 802
        $idHash = implode(' ', $id);
2093
2094 802
        if (isset($this->identityMap[$class->getRootClassName()][$idHash])) {
2095 305
            $entity = $this->identityMap[$class->getRootClassName()][$idHash];
2096 305
            $oid    = spl_object_id($entity);
2097
2098 305
            if (isset($hints[Query::HINT_REFRESH], $hints[Query::HINT_REFRESH_ENTITY])) {
2099 65
                $unmanagedProxy = $hints[Query::HINT_REFRESH_ENTITY];
2100 65
                if ($unmanagedProxy !== $entity
2101 65
                    && $unmanagedProxy instanceof GhostObjectInterface
2102 65
                    && $this->isIdentifierEquals($unmanagedProxy, $entity)
2103
                ) {
2104
                    // We will hydrate the given un-managed proxy anyway:
2105
                    // continue work, but consider it the entity from now on
2106 5
                    $entity = $unmanagedProxy;
2107
                }
2108
            }
2109
2110 305
            if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
2111 21
                $entity->setProxyInitializer(null);
2112
2113 21
                if ($entity instanceof NotifyPropertyChanged) {
2114 21
                    $entity->addPropertyChangedListener($this);
2115
                }
2116
            } else {
2117 291
                if (! isset($hints[Query::HINT_REFRESH])
2118 291
                    || (isset($hints[Query::HINT_REFRESH_ENTITY]) && $hints[Query::HINT_REFRESH_ENTITY] !== $entity)) {
2119 229
                    return $entity;
2120
                }
2121
            }
2122
2123
            // inject EntityManager upon refresh.
2124 103
            if ($entity instanceof EntityManagerAware) {
2125 3
                $entity->injectEntityManager($this->em, $class);
2126
            }
2127
2128 103
            $this->originalEntityData[$oid] = $data;
2129
        } else {
2130 662
            $entity = $this->newInstance($class);
2131 662
            $oid    = spl_object_id($entity);
2132
2133 662
            $this->entityIdentifiers[$oid]  = $id;
2134 662
            $this->entityStates[$oid]       = self::STATE_MANAGED;
2135 662
            $this->originalEntityData[$oid] = $data;
2136
2137 662
            $this->identityMap[$class->getRootClassName()][$idHash] = $entity;
2138
        }
2139
2140 695
        if ($entity instanceof NotifyPropertyChanged) {
2141 3
            $entity->addPropertyChangedListener($this);
2142
        }
2143
2144 695
        foreach ($data as $field => $value) {
2145 695
            $property = $class->getProperty($field);
2146
2147 695
            if ($property instanceof FieldMetadata) {
2148 693
                $property->setValue($entity, $value);
2149
            }
2150
        }
2151
2152
        // Loading the entity right here, if its in the eager loading map get rid of it there.
2153 695
        unset($this->eagerLoadingEntities[$class->getRootClassName()][$idHash]);
2154
2155 695
        if (isset($this->eagerLoadingEntities[$class->getRootClassName()]) && ! $this->eagerLoadingEntities[$class->getRootClassName()]) {
2156
            unset($this->eagerLoadingEntities[$class->getRootClassName()]);
2157
        }
2158
2159
        // Properly initialize any unfetched associations, if partial objects are not allowed.
2160 695
        if (isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
2161 34
            return $entity;
2162
        }
2163
2164 661
        foreach ($class->getDeclaredPropertiesIterator() as $field => $association) {
2165 661
            if (! ($association instanceof AssociationMetadata)) {
2166 661
                continue;
2167
            }
2168
2169
            // Check if the association is not among the fetch-joined associations already.
2170 565
            if (isset($hints['fetchAlias'], $hints['fetched'][$hints['fetchAlias']][$field])) {
2171 243
                continue;
2172
            }
2173
2174 542
            $targetEntity = $association->getTargetEntity();
2175 542
            $targetClass  = $this->em->getClassMetadata($targetEntity);
2176
2177 542
            if ($association instanceof ToManyAssociationMetadata) {
2178
                // Ignore if its a cached collection
2179 463
                if (isset($hints[Query::HINT_CACHE_ENABLED]) &&
2180 463
                    $association->getValue($entity) instanceof PersistentCollection) {
2181
                    continue;
2182
                }
2183
2184 463
                $hasDataField = isset($data[$field]);
2185
2186
                // use the given collection
2187 463
                if ($hasDataField && $data[$field] instanceof PersistentCollection) {
2188
                    $data[$field]->setOwner($entity, $association);
2189
2190
                    $association->setValue($entity, $data[$field]);
2191
2192
                    $this->originalEntityData[$oid][$field] = $data[$field];
2193
2194
                    continue;
2195
                }
2196
2197
                // Inject collection
2198 463
                $pColl = $association->wrap($entity, $hasDataField ? $data[$field] : [], $this->em);
2199
2200 463
                $pColl->setInitialized($hasDataField);
2201
2202 463
                $association->setValue($entity, $pColl);
2203
2204 463
                if ($association->getFetchMode() === FetchMode::EAGER) {
2205 4
                    $this->loadCollection($pColl);
2206 4
                    $pColl->takeSnapshot();
2207
                }
2208
2209 463
                $this->originalEntityData[$oid][$field] = $pColl;
2210
2211 463
                continue;
2212
            }
2213
2214 469
            if (! $association->isOwningSide()) {
2215
                // use the given entity association
2216 66
                if (isset($data[$field]) && is_object($data[$field]) &&
2217 66
                    isset($this->entityStates[spl_object_id($data[$field])])) {
2218 3
                    $inverseAssociation = $targetClass->getProperty($association->getMappedBy());
2219
2220 3
                    $association->setValue($entity, $data[$field]);
2221 3
                    $inverseAssociation->setValue($data[$field], $entity);
2222
2223 3
                    $this->originalEntityData[$oid][$field] = $data[$field];
2224
2225 3
                    continue;
2226
                }
2227
2228
                // Inverse side of x-to-one can never be lazy
2229 63
                $persister = $this->getEntityPersister($targetEntity);
2230
2231 63
                $association->setValue($entity, $persister->loadToOneEntity($association, $entity));
2232
2233 63
                continue;
2234
            }
2235
2236
            // use the entity association
2237 469
            if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_id($data[$field])])) {
2238 38
                $association->setValue($entity, $data[$field]);
2239
2240 38
                $this->originalEntityData[$oid][$field] = $data[$field];
2241
2242 38
                continue;
2243
            }
2244
2245 462
            $associatedId = [];
2246
2247
            // TODO: Is this even computed right in all cases of composite keys?
2248 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

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

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

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

Loading history...
2374 862
            return;
2375
        }
2376
2377
        // avoid infinite recursion
2378 7
        $eagerLoadingEntities       = $this->eagerLoadingEntities;
2379 7
        $this->eagerLoadingEntities = [];
2380
2381 7
        foreach ($eagerLoadingEntities as $entityName => $ids) {
2382 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...
2383
                continue;
2384
            }
2385
2386 7
            $class = $this->em->getClassMetadata($entityName);
2387
2388 7
            $this->getEntityPersister($entityName)->loadAll(
2389 7
                array_combine($class->identifier, [array_values($ids)])
0 ignored issues
show
Bug introduced by
It seems like array_combine($class->id...ay(array_values($ids))) can also be of type false; however, parameter $criteria of Doctrine\ORM\Persisters\...ityPersister::loadAll() does only seem to accept array, 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

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

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

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

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

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

Loading history...
2905 4
            throw ORMInvalidArgumentException::newEntitiesFoundThroughRelationships(
2906 4
                array_values($entitiesNeedingCascadePersist)
2907
            );
2908
        }
2909 1011
    }
2910
2911
    /**
2912
     * This method called by hydrators, and indicates that hydrator totally completed current hydration cycle.
2913
     * Unit of work able to fire deferred events, related to loading events here.
2914
     *
2915
     * @internal should be called internally from object hydrators
2916
     */
2917 878
    public function hydrationComplete()
2918
    {
2919 878
        $this->hydrationCompleteHandler->hydrationComplete();
2920 878
    }
2921
}
2922