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

541
        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...
542 1014
            $value = $property->getValue($entity);
543
544 1014
            if ($property instanceof ToManyAssociationMetadata && $value !== null) {
545 774
                if ($value instanceof PersistentCollection && $value->getOwner() === $entity) {
546 186
                    continue;
547
                }
548
549 771
                $value = $property->wrap($entity, $value, $this->em);
550
551 771
                $property->setValue($entity, $value);
552
553 771
                $actualData[$name] = $value;
554
555 771
                continue;
556
            }
557
558 1014
            if (( ! $class->isIdentifier($name)
559 1014
                    || ! $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

559
                    || ! $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...
560 1014
                    || ! $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

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

561
                    || $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...
562 1014
                ) && (! $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

562
                ) && (! $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...
563 1014
                $actualData[$name] = $value;
564
            }
565
        }
566
567 1014
        if (! isset($this->originalEntityData[$oid])) {
568
            // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
569
            // These result in an INSERT.
570 1010
            $this->originalEntityData[$oid] = $actualData;
571 1010
            $changeSet                      = [];
572
573 1010
            foreach ($actualData as $propName => $actualValue) {
574 990
                $property = $class->getProperty($propName);
575
576 990
                if (($property instanceof FieldMetadata) ||
577 990
                    ($property instanceof ToOneAssociationMetadata && $property->isOwningSide())) {
578 990
                    $changeSet[$propName] = [null, $actualValue];
579
                }
580
            }
581
582 1010
            $this->entityChangeSets[$oid] = $changeSet;
583
        } else {
584
            // Entity is "fully" MANAGED: it was already fully persisted before
585
            // and we have a copy of the original data
586 254
            $originalData           = $this->originalEntityData[$oid];
587 254
            $isChangeTrackingNotify = $class->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY;
588 254
            $changeSet              = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
589
                ? $this->entityChangeSets[$oid]
590 254
                : [];
591
592 254
            foreach ($actualData as $propName => $actualValue) {
593
                // skip field, its a partially omitted one!
594 243
                if (! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
595 40
                    continue;
596
                }
597
598 243
                $orgValue = $originalData[$propName];
599
600
                // skip if value haven't changed
601 243
                if ($orgValue === $actualValue) {
602 226
                    continue;
603
                }
604
605 109
                $property = $class->getProperty($propName);
606
607
                // Persistent collection was exchanged with the "originally"
608
                // created one. This can only mean it was cloned and replaced
609
                // on another entity.
610 109
                if ($actualValue instanceof PersistentCollection) {
611 8
                    $owner = $actualValue->getOwner();
612
613 8
                    if ($owner === null) { // cloned
614
                        $actualValue->setOwner($entity, $property);
615 8
                    } elseif ($owner !== $entity) { // no clone, we have to fix
616
                        if (! $actualValue->isInitialized()) {
617
                            $actualValue->initialize(); // we have to do this otherwise the cols share state
618
                        }
619
620
                        $newValue = clone $actualValue;
621
622
                        $newValue->setOwner($entity, $property);
623
624
                        $property->setValue($entity, $newValue);
625
                    }
626
                }
627
628
                switch (true) {
629 109
                    case ($property instanceof FieldMetadata):
630 58
                        if ($isChangeTrackingNotify) {
631
                            // Continue inside switch behaves as break.
632
                            // We are required to use continue 2, since we need to continue to next $actualData item
633
                            continue 2;
634
                        }
635
636 58
                        $changeSet[$propName] = [$orgValue, $actualValue];
637 58
                        break;
638
639 57
                    case ($property instanceof ToOneAssociationMetadata):
640 46
                        if ($property->isOwningSide()) {
641 20
                            $changeSet[$propName] = [$orgValue, $actualValue];
642
                        }
643
644 46
                        if ($orgValue !== null && $property->isOrphanRemoval()) {
645 4
                            $this->scheduleOrphanRemoval($orgValue);
646
                        }
647
648 46
                        break;
649
650 12
                    case ($property instanceof ToManyAssociationMetadata):
651
                        // Check if original value exists
652 9
                        if ($orgValue instanceof PersistentCollection) {
653
                            // A PersistentCollection was de-referenced, so delete it.
654 8
                            if (! $this->isCollectionScheduledForDeletion($orgValue)) {
655 8
                                $this->scheduleCollectionDeletion($orgValue);
656
657 8
                                $changeSet[$propName] = $orgValue; // Signal changeset, to-many associations will be ignored
658
                            }
659
                        }
660
661 9
                        break;
662
663 109
                    default:
664
                        // Do nothing
665
                }
666
            }
667
668 254
            if ($changeSet) {
669 84
                $this->entityChangeSets[$oid]   = $changeSet;
670 84
                $this->originalEntityData[$oid] = $actualData;
671 84
                $this->entityUpdates[$oid]      = $entity;
672
            }
673
        }
674
675
        // Look for changes in associations of the entity
676 1014
        foreach ($class->getDeclaredPropertiesIterator() as $property) {
677 1014
            if (! $property instanceof AssociationMetadata) {
678 1014
                continue;
679
            }
680
681 885
            $value = $property->getValue($entity);
682
683 885
            if ($value === null) {
684 623
                continue;
685
            }
686
687 861
            $this->computeAssociationChanges($property, $value);
688
689 853
            if ($property instanceof ManyToManyAssociationMetadata &&
690 853
                $value instanceof PersistentCollection &&
691 853
                ! isset($this->entityChangeSets[$oid]) &&
692 853
                $property->isOwningSide() &&
693 853
                $value->isDirty()) {
694 31
                $this->entityChangeSets[$oid]   = [];
695 31
                $this->originalEntityData[$oid] = $actualData;
696 853
                $this->entityUpdates[$oid]      = $entity;
697
            }
698
        }
699 1006
    }
700
701
    /**
702
     * Computes all the changes that have been done to entities and collections
703
     * since the last commit and stores these changes in the _entityChangeSet map
704
     * temporarily for access by the persisters, until the UoW commit is finished.
705
     */
706 1013
    public function computeChangeSets()
707
    {
708
        // Compute changes for INSERTed entities first. This must always happen.
709 1013
        $this->computeScheduleInsertsChangeSets();
710
711
        // Compute changes for other MANAGED entities. Change tracking policies take effect here.
712 1011
        foreach ($this->identityMap as $className => $entities) {
713 443
            $class = $this->em->getClassMetadata($className);
714
715
            // Skip class if instances are read-only
716 443
            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

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

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

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

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

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

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

1397
        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...
1398 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

1398
            || ! $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...
1399 6
            || ! $class->getProperty($class->getSingleIdentifierFieldName())->hasValueGenerator()
1400
        ) {
1401
            // Check for a version field, if available, to avoid a db lookup.
1402 5
            if ($class->isVersioned()) {
1403 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...
1404
                    ? self::STATE_DETACHED
1405 1
                    : self::STATE_NEW;
1406
            }
1407
1408
            // Last try before db lookup: check the identity map.
1409 4
            if ($this->tryGetById($flatId, $class->getRootClassName())) {
1410 1
                return self::STATE_DETACHED;
1411
            }
1412
1413
            // db lookup
1414 4
            if ($this->getEntityPersister($class->getClassName())->exists($entity)) {
1415
                return self::STATE_DETACHED;
1416
            }
1417
1418 4
            return self::STATE_NEW;
1419
        }
1420
1421 1
        if ($class->isIdentifierComposite()
1422 1
            || ! $class->getProperty($class->getSingleIdentifierFieldName()) instanceof FieldMetadata
1423 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

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

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

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