Failed Conditions
Pull Request — master (#7242)
by Gabriel
08:46
created

UnitOfWork::commit()   F

Complexity

Conditions 22
Paths 4862

Size

Total Lines 106
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 57
CRAP Score 22.0024

Importance

Changes 0
Metric Value
cc 22
eloc 58
nc 4862
nop 0
dl 0
loc 106
rs 2
c 0
b 0
f 0
ccs 57
cts 58
cp 0.9828
crap 22.0024

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 1402
    public function __construct(EntityManagerInterface $em)
305
    {
306 1402
        $this->em                       = $em;
307 1402
        $this->eventManager             = $em->getEventManager();
308 1402
        $this->listenersInvoker         = new ListenersInvoker($em);
309 1402
        $this->hasCache                 = $em->getConfiguration()->isSecondLevelCacheEnabled();
310 1402
        $this->instantiator             = new Instantiator();
311 1402
        $this->hydrationCompleteHandler = new HydrationCompleteHandler($this->listenersInvoker, $em);
312 1402
        $this->normalizeIdentifier      = new NormalizeIdentifier();
313 1402
    }
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 168
    public function commit()
331
    {
332
        // Raise preFlush
333 168
        if ($this->eventManager->hasListeners(Events::preFlush)) {
334 2
            $this->eventManager->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em));
335
        }
336
337 168
        $this->computeChangeSets();
338
339 166
        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 36
                $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 31
                $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 13
                $this->collectionUpdates ||
343 11
                $this->collectionDeletions ||
344 166
                $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 10
            $this->dispatchOnFlushEvent();
346 10
            $this->dispatchPostFlushEvent();
347
348 10
            return; // Nothing to do.
349
        }
350
351 161
        $this->assertThatThereAreNoUnintentionallyNonPersistedAssociations();
352
353 159
        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 5
            foreach ($this->orphanRemovals as $orphan) {
355 5
                $this->remove($orphan);
356
            }
357
        }
358
359 159
        $this->dispatchOnFlushEvent();
360
361
        // Now we need a commit order to maintain referential integrity
362 159
        $commitOrder = $this->getCommitOrder();
363
364 159
        $conn = $this->em->getConnection();
365 159
        $conn->beginTransaction();
366
367
        try {
368
            // Collection deletions (deletions of complete collections)
369 159
            foreach ($this->collectionDeletions as $collectionToDelete) {
370 2
                $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
371
            }
372
373 159
            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 155
                foreach ($commitOrder as $class) {
375 155
                    $this->executeInserts($class);
376
                }
377
            }
378
379 137
            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 20
                foreach ($commitOrder as $class) {
381 20
                    $this->executeUpdates($class);
382
                }
383
            }
384
385
            // Extra updates that were requested by persisters.
386 133
            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
                $this->executeExtraUpdates();
388
            }
389
390
            // Collection updates (deleteRows, updateRows, insertRows)
391 133
            foreach ($this->collectionUpdates as $collectionToUpdate) {
392 24
                $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
393
            }
394
395
            // Entity deletions come last and need to be in reverse commit order
396 133
            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 10
                foreach (array_reverse($commitOrder) as $committedEntityName) {
398 10
                    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 1
                        break; // just a performance optimisation
400
                    }
401
402 10
                    $this->executeDeletions($committedEntityName);
403
                }
404
            }
405
406 133
            $conn->commit();
407 26
        } catch (\Throwable $e) {
408 26
            $this->em->close();
409 26
            $conn->rollBack();
410
411 26
            $this->afterTransactionRolledBack();
412
413 26
            throw $e;
414
        }
415
416 133
        $this->afterTransactionComplete();
417
418
        // Take new snapshots from visited collections
419 133
        foreach ($this->visitedCollections as $coll) {
420 24
            $coll->takeSnapshot();
421
        }
422
423 133
        $this->dispatchPostFlushEvent();
424
425
        // Clean up
426 133
        $this->entityInsertions            =
427 133
        $this->entityUpdates               =
428 133
        $this->entityDeletions             =
429 133
        $this->extraUpdates                =
430 133
        $this->entityChangeSets            =
431 133
        $this->collectionUpdates           =
432 133
        $this->collectionDeletions         =
433 133
        $this->visitedCollections          =
434 133
        $this->scheduledForSynchronization =
435 133
        $this->orphanRemovals              = [];
436 133
    }
437
438
    /**
439
     * Computes the changesets of all entities scheduled for insertion.
440
     */
441 168
    private function computeScheduleInsertsChangeSets()
442
    {
443 168
        foreach ($this->entityInsertions as $entity) {
444 159
            $class = $this->em->getClassMetadata(get_class($entity));
445
446 159
            $this->computeChangeSet($class, $entity);
447
        }
448 166
    }
449
450
    /**
451
     * Executes any extra updates that have been scheduled.
452
     */
453
    private function executeExtraUpdates()
454
    {
455
        foreach ($this->extraUpdates as $oid => $update) {
456
            list ($entity, $changeset) = $update;
457
458
            $this->entityChangeSets[$oid] = $changeset;
459
460
//            echo 'Extra update: ';
461
//            \Doctrine\Common\Util\Debug::dump($changeset, 3);
462
463
            $this->getEntityPersister(get_class($entity))->update($entity);
464
        }
465
466
        $this->extraUpdates = [];
467
    }
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 155
        $oid  = spl_object_id($entity);
479 155
        $data = [];
480
481 155
        if (! isset($this->entityChangeSets[$oid])) {
482 2
            return $data;
483
        }
484
485 155
        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 170
    public function computeChangeSet(ClassMetadata $class, $entity)
522
    {
523 170
        $oid = spl_object_id($entity);
524
525 170
        if (isset($this->readOnlyObjects[$oid])) {
526
            return;
527
        }
528
529 170
        if ($class->inheritanceType !== InheritanceType::NONE) {
530 28
            $class = $this->em->getClassMetadata(get_class($entity));
531
        }
532
533 170
        $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preFlush) & ~ListenersInvoker::INVOKE_MANAGER;
534
535 170
        if ($invoke !== ListenersInvoker::INVOKE_NONE) {
536 11
            $this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke);
537
        }
538
539 170
        $actualData = [];
540
541 170
        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 170
            $value = $property->getValue($entity);
543
544 170
            if ($property instanceof ToManyAssociationMetadata && $value !== null) {
545 61
                if ($value instanceof PersistentCollection && $value->getOwner() === $entity) {
546 11
                    continue;
547
                }
548
549 60
                $value = $property->wrap($entity, $value, $this->em);
550
551 60
                $property->setValue($entity, $value);
552
553 60
                $actualData[$name] = $value;
554
555 60
                continue;
556
            }
557
558 170
            if (! (( ! $class->isIdentifier($name)
559 170
                    || ! $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 170
                    || ! $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 170
                    || $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 170
                )) || (! $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 170
                continue;
564
            }
565
566 31
            $actualData[$name] = $value;
567
        }
568
569 170
        if (! isset($this->originalEntityData[$oid])) {
570
            // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
571
            // These result in an INSERT.
572 166
            $this->originalEntityData[$oid] = $actualData;
573 166
            $changeSet                      = [];
574
575 166
            foreach ($actualData as $propName => $actualValue) {
576 85
                $property = $class->getProperty($propName);
577
578 85
                if (! (($property instanceof FieldMetadata)) &&
579 85
                    ! (($property instanceof ToOneAssociationMetadata && $property->isOwningSide()))) {
580 68
                    continue;
581
                }
582
583 27
                $changeSet[$propName] = [null, $actualValue];
584
            }
585
586 166
            $this->entityChangeSets[$oid] = $changeSet;
587
        } else {
588
            // Entity is "fully" MANAGED: it was already fully persisted before
589
            // and we have a copy of the original data
590 32
            $originalData           = $this->originalEntityData[$oid];
591 32
            $isChangeTrackingNotify = $class->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY;
592 32
            $changeSet              = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
593
                ? $this->entityChangeSets[$oid]
594 32
                : [];
595
596 32
            foreach ($actualData as $propName => $actualValue) {
597
                // skip field, its a partially omitted one!
598 15
                if (! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
599
                    continue;
600
                }
601
602 15
                $orgValue = $originalData[$propName];
603
604
                // skip if value haven't changed
605 15
                if ($orgValue === $actualValue) {
606 6
                    continue;
607
                }
608
609 13
                $property = $class->getProperty($propName);
610
611
                // Persistent collection was exchanged with the "originally"
612
                // created one. This can only mean it was cloned and replaced
613
                // on another entity.
614 13
                if ($actualValue instanceof PersistentCollection) {
615
                    $owner = $actualValue->getOwner();
616
617
                    if ($owner === null) { // cloned
618
                        $actualValue->setOwner($entity, $property);
619
                    } elseif ($owner !== $entity) { // no clone, we have to fix
620
                        if (! $actualValue->isInitialized()) {
621
                            $actualValue->initialize(); // we have to do this otherwise the cols share state
622
                        }
623
624
                        $newValue = clone $actualValue;
625
626
                        $newValue->setOwner($entity, $property);
627
628
                        $property->setValue($entity, $newValue);
629
                    }
630
                }
631
632
                switch (true) {
633 13
                    case ($property instanceof FieldMetadata):
634 13
                        if ($isChangeTrackingNotify) {
635
                            // Continue inside switch behaves as break.
636
                            // We are required to use continue 2, since we need to continue to next $actualData item
637
                            continue 2;
638
                        }
639
640 13
                        $changeSet[$propName] = [$orgValue, $actualValue];
641 13
                        break;
642
643
                    case ($property instanceof ToOneAssociationMetadata):
644
                        if ($property->isOwningSide()) {
645
                            $changeSet[$propName] = [$orgValue, $actualValue];
646
                        }
647
648
                        if ($orgValue !== null && $property->isOrphanRemoval()) {
649
                            $this->scheduleOrphanRemoval($orgValue);
650
                        }
651
652
                        break;
653
654
                    case ($property instanceof ToManyAssociationMetadata):
655
                        // Check if original value exists
656
                        if ($orgValue instanceof PersistentCollection) {
657
                            // A PersistentCollection was de-referenced, so delete it.
658
                            if (! $this->isCollectionScheduledForDeletion($orgValue)) {
659
                                $this->scheduleCollectionDeletion($orgValue);
660
661
                                $changeSet[$propName] = $orgValue; // Signal changeset, to-many associations will be ignored
662
                            }
663
                        }
664
665
                        break;
666
667 13
                    default:
668
                        // Do nothing
669
                }
670
            }
671
672 32
            if ($changeSet) {
673 13
                $this->entityChangeSets[$oid]   = $changeSet;
674 13
                $this->originalEntityData[$oid] = $actualData;
675 13
                $this->entityUpdates[$oid]      = $entity;
676
            }
677
        }
678
679
        // Look for changes in associations of the entity
680 170
        foreach ($class->getDeclaredPropertiesIterator() as $property) {
681 170
            if (! $property instanceof AssociationMetadata) {
682 170
                continue;
683
            }
684
685 107
            $value = $property->getValue($entity);
686
687 107
            if ($value === null) {
688 63
                continue;
689
            }
690
691 91
            $this->computeAssociationChanges($property, $value);
692
693 83
            if (! ($property instanceof ManyToManyAssociationMetadata) ||
694 39
                ! ($value instanceof PersistentCollection) ||
695 39
                isset($this->entityChangeSets[$oid]) ||
696 8
                ! $property->isOwningSide() ||
697 83
                ! $value->isDirty()) {
698 83
                continue;
699
            }
700
701 6
            $this->entityChangeSets[$oid]   = [];
702 6
            $this->originalEntityData[$oid] = $actualData;
703 6
            $this->entityUpdates[$oid]      = $entity;
704
        }
705 162
    }
706
707
    /**
708
     * Computes all the changes that have been done to entities and collections
709
     * since the last commit and stores these changes in the _entityChangeSet map
710
     * temporarily for access by the persisters, until the UoW commit is finished.
711
     */
712 168
    public function computeChangeSets()
713
    {
714
        // Compute changes for INSERTed entities first. This must always happen.
715 168
        $this->computeScheduleInsertsChangeSets();
716
717
        // Compute changes for other MANAGED entities. Change tracking policies take effect here.
718 166
        foreach ($this->identityMap as $className => $entities) {
719 44
            $class = $this->em->getClassMetadata($className);
720
721
            // Skip class if instances are read-only
722 44
            if ($class->isReadOnly()) {
0 ignored issues
show
Bug introduced by
The method isReadOnly() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

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

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

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

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

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

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

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

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

1421
        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...
1422 3
            || ! $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

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

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

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

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