Failed Conditions
Pull Request — 2.6 (#7882)
by
unknown
06:45
created

UnitOfWork::mergeEntityStateIntoManagedCopy()   D

Complexity

Conditions 23
Paths 67

Size

Total Lines 96
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 36
CRAP Score 38.4112

Importance

Changes 0
Metric Value
eloc 55
dl 0
loc 96
ccs 36
cts 52
cp 0.6923
rs 4.1666
c 0
b 0
f 0
cc 23
nc 67
nop 2
crap 38.4112

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
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\ORM;
21
22
use Doctrine\Common\Collections\ArrayCollection;
23
use Doctrine\Common\Collections\Collection;
24
use Doctrine\Common\NotifyPropertyChanged;
25
use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService;
26
use Doctrine\Common\Persistence\ObjectManagerAware;
27
use Doctrine\Common\PropertyChangedListener;
28
use Doctrine\DBAL\LockMode;
29
use Doctrine\ORM\Cache\Persister\CachedPersister;
30
use Doctrine\ORM\Event\LifecycleEventArgs;
31
use Doctrine\ORM\Event\ListenersInvoker;
32
use Doctrine\ORM\Event\OnFlushEventArgs;
33
use Doctrine\ORM\Event\PostFlushEventArgs;
34
use Doctrine\ORM\Event\PreFlushEventArgs;
35
use Doctrine\ORM\Event\PreUpdateEventArgs;
36
use Doctrine\ORM\Internal\HydrationCompleteHandler;
37
use Doctrine\ORM\Mapping\ClassMetadata;
38
use Doctrine\ORM\Mapping\Reflection\ReflectionPropertiesGetter;
39
use Doctrine\ORM\Persisters\Collection\ManyToManyPersister;
40
use Doctrine\ORM\Persisters\Collection\OneToManyPersister;
41
use Doctrine\ORM\Persisters\Entity\BasicEntityPersister;
42
use Doctrine\ORM\Persisters\Entity\JoinedSubclassPersister;
43
use Doctrine\ORM\Persisters\Entity\SingleTablePersister;
44
use Doctrine\ORM\Proxy\Proxy;
45
use Doctrine\ORM\Utility\IdentifierFlattener;
46
use InvalidArgumentException;
47
use Throwable;
48
use UnexpectedValueException;
49
50
/**
51
 * The UnitOfWork is responsible for tracking changes to objects during an
52
 * "object-level" transaction and for writing out changes to the database
53
 * in the correct order.
54
 *
55
 * Internal note: This class contains highly performance-sensitive code.
56
 *
57
 * @since       2.0
58
 * @author      Benjamin Eberlei <[email protected]>
59
 * @author      Guilherme Blanco <[email protected]>
60
 * @author      Jonathan Wage <[email protected]>
61
 * @author      Roman Borschel <[email protected]>
62
 * @author      Rob Caiger <[email protected]>
63
 */
64
class UnitOfWork implements PropertyChangedListener
65
{
66
    /**
67
     * An entity is in MANAGED state when its persistence is managed by an EntityManager.
68
     */
69
    const STATE_MANAGED = 1;
70
71
    /**
72
     * An entity is new if it has just been instantiated (i.e. using the "new" operator)
73
     * and is not (yet) managed by an EntityManager.
74
     */
75
    const STATE_NEW = 2;
76
77
    /**
78
     * A detached entity is an instance with persistent state and identity that is not
79
     * (or no longer) associated with an EntityManager (and a UnitOfWork).
80
     */
81
    const STATE_DETACHED = 3;
82
83
    /**
84
     * A removed entity instance is an instance with a persistent identity,
85
     * associated with an EntityManager, whose persistent state will be deleted
86
     * on commit.
87
     */
88
    const STATE_REMOVED = 4;
89
90
    /**
91
     * Hint used to collect all primary keys of associated entities during hydration
92
     * and execute it in a dedicated query afterwards
93
     * @see https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#temporarily-change-fetch-mode-in-dql
94
     */
95
    const HINT_DEFEREAGERLOAD = 'deferEagerLoad';
96
97
    /**
98
     * The identity map that holds references to all managed entities that have
99
     * an identity. The entities are grouped by their class name.
100
     * Since all classes in a hierarchy must share the same identifier set,
101
     * we always take the root class name of the hierarchy.
102
     *
103
     * @var array
104
     */
105
    private $identityMap = [];
106
107
    /**
108
     * Map of all identifiers of managed entities.
109
     * Keys are object ids (spl_object_hash).
110
     *
111
     * @var array
112
     */
113
    private $entityIdentifiers = [];
114
115
    /**
116
     * Map of the original entity data of managed entities.
117
     * Keys are object ids (spl_object_hash). This is used for calculating changesets
118
     * at commit time.
119
     *
120
     * Internal note: Note that PHPs "copy-on-write" behavior helps a lot with memory usage.
121
     *                A value will only really be copied if the value in the entity is modified
122
     *                by the user.
123
     *
124
     * @var array
125
     */
126
    private $originalEntityData = [];
127
128
    /**
129
     * Map of entity changes. Keys are object ids (spl_object_hash).
130
     * Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
131
     *
132
     * @var array
133
     */
134
    private $entityChangeSets = [];
135
136
    /**
137
     * The (cached) states of any known entities.
138
     * Keys are object ids (spl_object_hash).
139
     *
140
     * @var array
141
     */
142
    private $entityStates = [];
143
144
    /**
145
     * Map of entities that are scheduled for dirty checking at commit time.
146
     * This is only used for entities with a change tracking policy of DEFERRED_EXPLICIT.
147
     * Keys are object ids (spl_object_hash).
148
     *
149
     * @var array
150
     */
151
    private $scheduledForSynchronization = [];
152
153
    /**
154
     * A list of all pending entity insertions.
155
     *
156
     * @var array
157
     */
158
    private $entityInsertions = [];
159
160
    /**
161
     * A list of all pending entity updates.
162
     *
163
     * @var array
164
     */
165
    private $entityUpdates = [];
166
167
    /**
168
     * Any pending extra updates that have been scheduled by persisters.
169
     *
170
     * @var array
171
     */
172
    private $extraUpdates = [];
173
174
    /**
175
     * A list of all pending entity deletions.
176
     *
177
     * @var array
178
     */
179
    private $entityDeletions = [];
180
181
    /**
182
     * New entities that were discovered through relationships that were not
183
     * marked as cascade-persist. During flush, this array is populated and
184
     * then pruned of any entities that were discovered through a valid
185
     * cascade-persist path. (Leftovers cause an error.)
186
     *
187
     * Keys are OIDs, payload is a two-item array describing the association
188
     * and the entity.
189
     *
190
     * @var object[][]|array[][] indexed by respective object spl_object_hash()
191
     */
192
    private $nonCascadedNewDetectedEntities = [];
193
194
    /**
195
     * All pending collection deletions.
196
     *
197
     * @var array
198
     */
199
    private $collectionDeletions = [];
200
201
    /**
202
     * All pending collection updates.
203
     *
204
     * @var array
205
     */
206
    private $collectionUpdates = [];
207
208
    /**
209
     * List of collections visited during changeset calculation on a commit-phase of a UnitOfWork.
210
     * At the end of the UnitOfWork all these collections will make new snapshots
211
     * of their data.
212
     *
213
     * @var array
214
     */
215
    private $visitedCollections = [];
216
217
    /**
218
     * The EntityManager that "owns" this UnitOfWork instance.
219
     *
220
     * @var EntityManagerInterface
221
     */
222
    private $em;
223
224
    /**
225
     * The entity persister instances used to persist entity instances.
226
     *
227
     * @var array
228
     */
229
    private $persisters = [];
230
231
    /**
232
     * The collection persister instances used to persist collections.
233
     *
234
     * @var array
235
     */
236
    private $collectionPersisters = [];
237
238
    /**
239
     * The EventManager used for dispatching events.
240
     *
241
     * @var \Doctrine\Common\EventManager
242
     */
243
    private $evm;
244
245
    /**
246
     * The ListenersInvoker used for dispatching events.
247
     *
248
     * @var \Doctrine\ORM\Event\ListenersInvoker
249
     */
250
    private $listenersInvoker;
251
252
    /**
253
     * The IdentifierFlattener used for manipulating identifiers
254
     *
255
     * @var \Doctrine\ORM\Utility\IdentifierFlattener
256
     */
257
    private $identifierFlattener;
258
259
    /**
260
     * Orphaned entities that are scheduled for removal.
261
     *
262
     * @var array
263
     */
264
    private $orphanRemovals = [];
265
266
    /**
267
     * Read-Only objects are never evaluated
268
     *
269
     * @var array
270
     */
271
    private $readOnlyObjects = [];
272
273
    /**
274
     * Map of Entity Class-Names and corresponding IDs that should eager loaded when requested.
275
     *
276
     * @var array
277
     */
278
    private $eagerLoadingEntities = [];
279
280
    /**
281
     * @var boolean
282
     */
283
    protected $hasCache = false;
284
285
    /**
286
     * Helper for handling completion of hydration
287
     *
288
     * @var HydrationCompleteHandler
289
     */
290
    private $hydrationCompleteHandler;
291
292
    /**
293
     * @var ReflectionPropertiesGetter
294
     */
295
    private $reflectionPropertiesGetter;
296
297
    /**
298
     * Initializes a new UnitOfWork instance, bound to the given EntityManager.
299
     *
300
     * @param EntityManagerInterface $em
301
     */
302 1626
    public function __construct(EntityManagerInterface $em)
303
    {
304 1626
        $this->em                         = $em;
305 1626
        $this->evm                        = $em->getEventManager();
306 1626
        $this->listenersInvoker           = new ListenersInvoker($em);
307 1626
        $this->hasCache                   = $em->getConfiguration()->isSecondLevelCacheEnabled();
308 1626
        $this->identifierFlattener        = new IdentifierFlattener($this, $em->getMetadataFactory());
309 1626
        $this->hydrationCompleteHandler   = new HydrationCompleteHandler($this->listenersInvoker, $em);
310 1626
        $this->reflectionPropertiesGetter = new ReflectionPropertiesGetter(new RuntimeReflectionService());
311 1626
    }
312
313
    /**
314
     * Commits the UnitOfWork, executing all operations that have been postponed
315
     * up to this point. The state of all managed entities will be synchronized with
316
     * the database.
317
     *
318
     * The operations are executed in the following order:
319
     *
320
     * 1) All entity insertions
321
     * 2) All entity updates
322
     * 3) All collection deletions
323
     * 4) All collection updates
324
     * 5) All entity deletions
325
     *
326
     * @param null|object|array $entity
327
     *
328
     * @return void
329
     *
330
     * @throws \Exception
331
     */
332 232
    public function commit($entity = null)
333
    {
334
        // Raise preFlush
335 232
        if ($this->evm->hasListeners(Events::preFlush)) {
336 2
            $this->evm->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em));
337
        }
338
339
        // Compute changes done since last commit.
340 232
        if (null === $entity) {
341 224
            $this->computeChangeSets();
342 9
        } elseif (is_object($entity)) {
343 8
            $this->computeSingleEntityChangeSet($entity);
344 1
        } elseif (is_array($entity)) {
0 ignored issues
show
introduced by
The condition is_array($entity) is always true.
Loading history...
345 1
            foreach ($entity as $object) {
346 1
                $this->computeSingleEntityChangeSet($object);
347
            }
348
        }
349
350 229
        if ( ! ($this->entityInsertions ||
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityInsertions 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...
351 59
                $this->entityDeletions ||
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityDeletions 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...
352 51
                $this->entityUpdates ||
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityUpdates 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...
353 12
                $this->collectionUpdates ||
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->collectionUpdates 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...
354 12
                $this->collectionDeletions ||
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->collectionDeletions 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...
355 229
                $this->orphanRemovals)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->orphanRemovals 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...
356 11
            $this->dispatchOnFlushEvent();
357 11
            $this->dispatchPostFlushEvent();
358
359 11
            $this->postCommitCleanup($entity);
360
361 11
            return; // Nothing to do.
362
        }
363
364 225
        $this->assertThatThereAreNoUnintentionallyNonPersistedAssociations();
365
366 223
        if ($this->orphanRemovals) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->orphanRemovals 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...
367 5
            foreach ($this->orphanRemovals as $orphan) {
368 5
                $this->remove($orphan);
369
            }
370
        }
371
372 223
        $this->dispatchOnFlushEvent();
373
374
        // Now we need a commit order to maintain referential integrity
375 223
        $commitOrder = $this->getCommitOrder();
376
377 223
        $conn = $this->em->getConnection();
378 223
        $conn->beginTransaction();
379
380
        try {
381
            // Collection deletions (deletions of complete collections)
382 223
            foreach ($this->collectionDeletions as $collectionToDelete) {
383 2
                $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
384
            }
385
386 223
            if ($this->entityInsertions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityInsertions 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...
387 219
                foreach ($commitOrder as $class) {
388 219
                    $this->executeInserts($class);
389
                }
390
            }
391
392 208
            if ($this->entityUpdates) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityUpdates 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...
393 45
                foreach ($commitOrder as $class) {
394 45
                    $this->executeUpdates($class);
395
                }
396
            }
397
398
            // Extra updates that were requested by persisters.
399 204
            if ($this->extraUpdates) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->extraUpdates 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...
400
                $this->executeExtraUpdates();
401
            }
402
403
            // Collection updates (deleteRows, updateRows, insertRows)
404 204
            foreach ($this->collectionUpdates as $collectionToUpdate) {
405 43
                $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
406
            }
407
408
            // Entity deletions come last and need to be in reverse commit order
409 204
            if ($this->entityDeletions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityDeletions 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...
410 17
                for ($count = count($commitOrder), $i = $count - 1; $i >= 0 && $this->entityDeletions; --$i) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityDeletions 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...
411 17
                    $this->executeDeletions($commitOrder[$i]);
412
                }
413
            }
414
415 204
            $conn->commit();
416 22
        } catch (Throwable $e) {
417 22
            $this->em->close();
418 22
            $conn->rollBack();
419
420 22
            $this->afterTransactionRolledBack();
421
422 22
            throw $e;
423
        }
424
425 204
        $this->afterTransactionComplete();
426
427
        // Take new snapshots from visited collections
428 204
        foreach ($this->visitedCollections as $coll) {
429 43
            $coll->takeSnapshot();
430
        }
431
432 204
        $this->dispatchPostFlushEvent();
433
434 203
        $this->postCommitCleanup($entity);
435 203
    }
436
437
    /**
438
     * @param null|object|object[] $entity
439
     */
440 207
    private function postCommitCleanup($entity) : void
441
    {
442 207
        $this->entityInsertions =
443 207
        $this->entityUpdates =
444 207
        $this->entityDeletions =
445 207
        $this->extraUpdates =
446 207
        $this->collectionUpdates =
447 207
        $this->nonCascadedNewDetectedEntities =
448 207
        $this->collectionDeletions =
449 207
        $this->visitedCollections =
450 207
        $this->orphanRemovals = [];
451
452 207
        if (null === $entity) {
453 200
            $this->entityChangeSets = $this->scheduledForSynchronization = [];
454
455 200
            return;
456
        }
457
458 8
        $entities = \is_object($entity)
459 7
            ? [$entity]
460 8
            : $entity;
461
462 8
        foreach ($entities as $object) {
463 8
            $oid = \spl_object_hash($object);
464
465 8
            $this->clearEntityChangeSet($oid);
466
467 8
            unset($this->scheduledForSynchronization[$this->em->getClassMetadata(\get_class($object))->rootEntityName][$oid]);
0 ignored issues
show
Bug introduced by
Accessing rootEntityName on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
468
        }
469 8
    }
470
471
    /**
472
     * Computes the changesets of all entities scheduled for insertion.
473
     *
474
     * @return void
475
     */
476 231
    private function computeScheduleInsertsChangeSets()
477
    {
478 231
        foreach ($this->entityInsertions as $entity) {
479 223
            $class = $this->em->getClassMetadata(get_class($entity));
480
481 223
            $this->computeChangeSet($class, $entity);
482
        }
483 229
    }
484
485
    /**
486
     * Only flushes the given entity according to a ruleset that keeps the UoW consistent.
487
     *
488
     * 1. All entities scheduled for insertion, (orphan) removals and changes in collections are processed as well!
489
     * 2. Read Only entities are skipped.
490
     * 3. Proxies are skipped.
491
     * 4. Only if entity is properly managed.
492
     *
493
     * @param object $entity
494
     *
495
     * @return void
496
     *
497
     * @throws \InvalidArgumentException
498
     */
499 9
    private function computeSingleEntityChangeSet($entity)
500
    {
501 9
        $state = $this->getEntityState($entity);
502
503 9
        if ($state !== self::STATE_MANAGED && $state !== self::STATE_REMOVED) {
504 1
            throw new \InvalidArgumentException("Entity has to be managed or scheduled for removal for single computation " . self::objToStr($entity));
505
        }
506
507 8
        $class = $this->em->getClassMetadata(get_class($entity));
508
509 8
        if ($state === self::STATE_MANAGED && $class->isChangeTrackingDeferredImplicit()) {
510 8
            $this->persist($entity);
511
        }
512
513
        // Compute changes for INSERTed entities first. This must always happen even in this case.
514 8
        $this->computeScheduleInsertsChangeSets();
515
516 8
        if ($class->isReadOnly) {
0 ignored issues
show
Bug introduced by
Accessing isReadOnly on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
517
            return;
518
        }
519
520
        // Ignore uninitialized proxy objects
521 8
        if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
0 ignored issues
show
Bug introduced by
Accessing __isInitialized__ on the interface Doctrine\ORM\Proxy\Proxy suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
522
            return;
523
        }
524
525
        // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
526 8
        $oid = spl_object_hash($entity);
527
528 8
        if ( ! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
529 1
            $this->computeChangeSet($class, $entity);
530
        }
531 8
    }
532
533
    /**
534
     * Executes any extra updates that have been scheduled.
535
     */
536
    private function executeExtraUpdates()
537
    {
538
        foreach ($this->extraUpdates as $oid => $update) {
539
            list ($entity, $changeset) = $update;
540
541
            $this->entityChangeSets[$oid] = $changeset;
542
            $this->getEntityPersister(get_class($entity))->update($entity);
543
        }
544
545
        $this->extraUpdates = [];
546
    }
547
548
    /**
549
     * Gets the changeset for an entity.
550
     *
551
     * @param object $entity
552
     *
553
     * @return array
554
     */
555
    public function & getEntityChangeSet($entity)
556
    {
557 217
        $oid  = spl_object_hash($entity);
558 217
        $data = [];
559
560 217
        if (!isset($this->entityChangeSets[$oid])) {
561 3
            return $data;
562
        }
563
564 217
        return $this->entityChangeSets[$oid];
565
    }
566
567
    /**
568
     * Computes the changes that happened to a single entity.
569
     *
570
     * Modifies/populates the following properties:
571
     *
572
     * {@link _originalEntityData}
573
     * If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
574
     * then it was not fetched from the database and therefore we have no original
575
     * entity data yet. All of the current entity data is stored as the original entity data.
576
     *
577
     * {@link _entityChangeSets}
578
     * The changes detected on all properties of the entity are stored there.
579
     * A change is a tuple array where the first entry is the old value and the second
580
     * entry is the new value of the property. Changesets are used by persisters
581
     * to INSERT/UPDATE the persistent entity state.
582
     *
583
     * {@link _entityUpdates}
584
     * If the entity is already fully MANAGED (has been fetched from the database before)
585
     * and any changes to its properties are detected, then a reference to the entity is stored
586
     * there to mark it for an update.
587
     *
588
     * {@link _collectionDeletions}
589
     * If a PersistentCollection has been de-referenced in a fully MANAGED entity,
590
     * then this collection is marked for deletion.
591
     *
592
     * @ignore
593
     *
594
     * @internal Don't call from the outside.
595
     *
596
     * @param ClassMetadata $class  The class descriptor of the entity.
597
     * @param object        $entity The entity for which to compute the changes.
598
     *
599
     * @return void
600
     */
601 233
    public function computeChangeSet(ClassMetadata $class, $entity)
602
    {
603 233
        $oid = spl_object_hash($entity);
604
605 233
        if (isset($this->readOnlyObjects[$oid])) {
606 1
            return;
607
        }
608
609 233
        if ( ! $class->isInheritanceTypeNone()) {
610 42
            $class = $this->em->getClassMetadata(get_class($entity));
611
        }
612
613 233
        $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preFlush) & ~ListenersInvoker::INVOKE_MANAGER;
614
615 233
        if ($invoke !== ListenersInvoker::INVOKE_NONE) {
616 2
            $this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke);
617
        }
618
619 233
        $actualData = [];
620
621 233
        foreach ($class->reflFields as $name => $refProp) {
622 233
            $value = $refProp->getValue($entity);
623
624 233
            if ($class->isCollectionValuedAssociation($name) && $value !== null) {
625 66
                if ($value instanceof PersistentCollection) {
626 24
                    if ($value->getOwner() === $entity) {
627 24
                        continue;
628
                    }
629
630
                    $value = new ArrayCollection($value->getValues());
631
                }
632
633
                // If $value is not a Collection then use an ArrayCollection.
634 64
                if ( ! $value instanceof Collection) {
635 7
                    $value = new ArrayCollection($value);
636
                }
637
638 64
                $assoc = $class->associationMappings[$name];
639
640
                // Inject PersistentCollection
641 64
                $value = new PersistentCollection(
642 64
                    $this->em, $this->em->getClassMetadata($assoc['targetEntity']), $value
643
                );
644 64
                $value->setOwner($entity, $assoc);
645 64
                $value->setDirty( ! $value->isEmpty());
646
647 64
                $class->reflFields[$name]->setValue($entity, $value);
648
649 64
                $actualData[$name] = $value;
650
651 64
                continue;
652
            }
653
654 233
            if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) && ($name !== $class->versionField)) {
655 233
                $actualData[$name] = $value;
656
            }
657
        }
658
659 233
        if ( ! isset($this->originalEntityData[$oid])) {
660
            // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
661
            // These result in an INSERT.
662 229
            $this->originalEntityData[$oid] = $actualData;
663 229
            $changeSet = [];
664
665 229
            foreach ($actualData as $propName => $actualValue) {
666 205
                if ( ! isset($class->associationMappings[$propName])) {
667 187
                    $changeSet[$propName] = [null, $actualValue];
668
669 187
                    continue;
670
                }
671
672 86
                $assoc = $class->associationMappings[$propName];
673
674 86
                if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
675 86
                    $changeSet[$propName] = [null, $actualValue];
676
                }
677
            }
678
679 229
            $this->entityChangeSets[$oid] = $changeSet;
680
        } else {
681
            // Entity is "fully" MANAGED: it was already fully persisted before
682
            // and we have a copy of the original data
683 53
            $originalData           = $this->originalEntityData[$oid];
684 53
            $isChangeTrackingNotify = $class->isChangeTrackingNotify();
685 53
            $changeSet              = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
686
                ? $this->entityChangeSets[$oid]
687 53
                : [];
688
689 53
            foreach ($actualData as $propName => $actualValue) {
690
                // skip field, its a partially omitted one!
691 41
                if ( ! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
692 1
                    continue;
693
                }
694
695 41
                $orgValue = $originalData[$propName];
696
697
                // skip if value haven't changed
698 41
                if ($orgValue === $actualValue) {
699 27
                    continue;
700
                }
701
702
                // if regular field
703 29
                if ( ! isset($class->associationMappings[$propName])) {
704 28
                    if ($isChangeTrackingNotify) {
705
                        continue;
706
                    }
707
708 28
                    $changeSet[$propName] = [$orgValue, $actualValue];
709
710 28
                    continue;
711
                }
712
713 2
                $assoc = $class->associationMappings[$propName];
714
715
                // Persistent collection was exchanged with the "originally"
716
                // created one. This can only mean it was cloned and replaced
717
                // on another entity.
718 2
                if ($actualValue instanceof PersistentCollection) {
719
                    $owner = $actualValue->getOwner();
720
                    if ($owner === null) { // cloned
721
                        $actualValue->setOwner($entity, $assoc);
722
                    } else if ($owner !== $entity) { // no clone, we have to fix
723
                        if (!$actualValue->isInitialized()) {
724
                            $actualValue->initialize(); // we have to do this otherwise the cols share state
725
                        }
726
                        $newValue = clone $actualValue;
727
                        $newValue->setOwner($entity, $assoc);
728
                        $class->reflFields[$propName]->setValue($entity, $newValue);
729
                    }
730
                }
731
732 2
                if ($orgValue instanceof PersistentCollection) {
733
                    // A PersistentCollection was de-referenced, so delete it.
734
                    $coid = spl_object_hash($orgValue);
735
736
                    if (isset($this->collectionDeletions[$coid])) {
737
                        continue;
738
                    }
739
740
                    $this->collectionDeletions[$coid] = $orgValue;
741
                    $changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored.
742
743
                    continue;
744
                }
745
746 2
                if ($assoc['type'] & ClassMetadata::TO_ONE) {
747 2
                    if ($assoc['isOwningSide']) {
748 2
                        $changeSet[$propName] = [$orgValue, $actualValue];
749
                    }
750
751 2
                    if ($orgValue !== null && $assoc['orphanRemoval']) {
752 2
                        $this->scheduleOrphanRemoval($orgValue);
753
                    }
754
                }
755
            }
756
757 53
            if ($changeSet) {
758 29
                $this->entityChangeSets[$oid]   = $changeSet;
759 29
                $this->originalEntityData[$oid] = $actualData;
760 29
                $this->entityUpdates[$oid]      = $entity;
761
            }
762
        }
763
764
        // Look for changes in associations of the entity
765 233
        foreach ($class->associationMappings as $field => $assoc) {
766 86
            if (($val = $class->reflFields[$field]->getValue($entity)) === null) {
767 25
                continue;
768
            }
769
770 79
            $this->computeAssociationChanges($assoc, $val);
771
772 71
            if ( ! isset($this->entityChangeSets[$oid]) &&
773 71
                $assoc['isOwningSide'] &&
774 71
                $assoc['type'] == ClassMetadata::MANY_TO_MANY &&
775 71
                $val instanceof PersistentCollection &&
776 71
                $val->isDirty()) {
777
778 16
                $this->entityChangeSets[$oid]   = [];
779 16
                $this->originalEntityData[$oid] = $actualData;
780 71
                $this->entityUpdates[$oid]      = $entity;
781
            }
782
        }
783 225
    }
784
785
    /**
786
     * Computes all the changes that have been done to entities and collections
787
     * since the last commit and stores these changes in the _entityChangeSet map
788
     * temporarily for access by the persisters, until the UoW commit is finished.
789
     *
790
     * @return void
791
     */
792 224
    public function computeChangeSets()
793
    {
794
        // Compute changes for INSERTed entities first. This must always happen.
795 224
        $this->computeScheduleInsertsChangeSets();
796
797
        // Compute changes for other MANAGED entities. Change tracking policies take effect here.
798 222
        foreach ($this->identityMap as $className => $entities) {
799 98
            $class = $this->em->getClassMetadata($className);
800
801
            // Skip class if instances are read-only
802 98
            if ($class->isReadOnly) {
0 ignored issues
show
Bug introduced by
Accessing isReadOnly on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
803 1
                continue;
804
            }
805
806
            // If change tracking is explicit or happens through notification, then only compute
807
            // changes on entities of that type that are explicitly marked for synchronization.
808
            switch (true) {
809 97
                case ($class->isChangeTrackingDeferredImplicit()):
810 94
                    $entitiesToProcess = $entities;
811 94
                    break;
812
813 4
                case (isset($this->scheduledForSynchronization[$className])):
814 3
                    $entitiesToProcess = $this->scheduledForSynchronization[$className];
815 3
                    break;
816
817
                default:
818 2
                    $entitiesToProcess = [];
819
820
            }
821
822 97
            foreach ($entitiesToProcess as $entity) {
823
                // Ignore uninitialized proxy objects
824 90
                if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
0 ignored issues
show
Bug introduced by
Accessing __isInitialized__ on the interface Doctrine\ORM\Proxy\Proxy suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
825 1
                    continue;
826
                }
827
828
                // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
829 89
                $oid = spl_object_hash($entity);
830
831 89
                if ( ! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
832 97
                    $this->computeChangeSet($class, $entity);
833
                }
834
            }
835
        }
836 222
    }
837
838
    /**
839
     * Computes the changes of an association.
840
     *
841
     * @param array $assoc The association mapping.
842
     * @param mixed $value The value of the association.
843
     *
844
     * @throws ORMInvalidArgumentException
845
     * @throws ORMException
846
     *
847
     * @return void
848
     */
849 79
    private function computeAssociationChanges($assoc, $value)
850
    {
851 79
        if ($value instanceof Proxy && ! $value->__isInitialized__) {
0 ignored issues
show
Bug introduced by
Accessing __isInitialized__ on the interface Doctrine\ORM\Proxy\Proxy suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
852 1
            return;
853
        }
854
855 78
        if ($value instanceof PersistentCollection && $value->isDirty()) {
856 51
            $coid = spl_object_hash($value);
857
858 51
            $this->collectionUpdates[$coid] = $value;
859 51
            $this->visitedCollections[$coid] = $value;
860
        }
861
862
        // Look through the entities, and in any of their associations,
863
        // for transient (new) entities, recursively. ("Persistence by reachability")
864
        // Unwrap. Uninitialized collections will simply be empty.
865 78
        $unwrappedValue = ($assoc['type'] & ClassMetadata::TO_ONE) ? [$value] : $value->unwrap();
866 78
        $targetClass    = $this->em->getClassMetadata($assoc['targetEntity']);
867
868 78
        foreach ($unwrappedValue as $key => $entry) {
869 68
            if (! ($entry instanceof $targetClass->name)) {
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
870 8
                throw ORMInvalidArgumentException::invalidAssociation($targetClass, $assoc, $entry);
871
            }
872
873 60
            $state = $this->getEntityState($entry, self::STATE_NEW);
874
875 60
            if ( ! ($entry instanceof $assoc['targetEntity'])) {
876
                throw ORMException::unexpectedAssociationValue($assoc['sourceEntity'], $assoc['fieldName'], get_class($entry), $assoc['targetEntity']);
877
            }
878
879
            switch ($state) {
880 60
                case self::STATE_NEW:
881 6
                    if ( ! $assoc['isCascadePersist']) {
882
                        /*
883
                         * For now just record the details, because this may
884
                         * not be an issue if we later discover another pathway
885
                         * through the object-graph where cascade-persistence
886
                         * is enabled for this object.
887
                         */
888 4
                        $this->nonCascadedNewDetectedEntities[\spl_object_hash($entry)] = [$assoc, $entry];
889
890 4
                        break;
891
                    }
892
893 3
                    $this->persistNew($targetClass, $entry);
894 3
                    $this->computeChangeSet($targetClass, $entry);
895
896 3
                    break;
897
898 54
                case self::STATE_REMOVED:
899
                    // Consume the $value as array (it's either an array or an ArrayAccess)
900
                    // and remove the element from Collection.
901
                    if ($assoc['type'] & ClassMetadata::TO_MANY) {
902
                        unset($value[$key]);
903
                    }
904
                    break;
905
906 54
                case self::STATE_DETACHED:
907
                    // Can actually not happen right now as we assume STATE_NEW,
908
                    // so the exception will be raised from the DBAL layer (constraint violation).
909
                    throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($assoc, $entry);
910
                    break;
911
912 60
                default:
913
                    // MANAGED associated entities are already taken into account
914
                    // during changeset calculation anyway, since they are in the identity map.
915
            }
916
        }
917 70
    }
918
919
    /**
920
     * @param \Doctrine\ORM\Mapping\ClassMetadata $class
921
     * @param object                              $entity
922
     *
923
     * @return void
924
     */
925 252
    private function persistNew($class, $entity)
926
    {
927 252
        $oid    = spl_object_hash($entity);
928 252
        $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::prePersist);
929
930 252
        if ($invoke !== ListenersInvoker::INVOKE_NONE) {
931 5
            $this->listenersInvoker->invoke($class, Events::prePersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
932
        }
933
934 252
        $idGen = $class->idGenerator;
935
936 252
        if ( ! $idGen->isPostInsertGenerator()) {
937 60
            $idValue = $idGen->generate($this->em, $entity);
938
939 60
            if ( ! $idGen instanceof \Doctrine\ORM\Id\AssignedGenerator) {
940 2
                $idValue = [$class->getSingleIdentifierFieldName() => $this->convertSingleFieldIdentifierToPHPValue($class, $idValue)];
941
942 2
                $class->setIdentifierValues($entity, $idValue);
943
            }
944
945
            // Some identifiers may be foreign keys to new entities.
946
            // In this case, we don't have the value yet and should treat it as if we have a post-insert generator
947 60
            if (! $this->hasMissingIdsWhichAreForeignKeys($class, $idValue)) {
948 60
                $this->entityIdentifiers[$oid] = $idValue;
949
            }
950
        }
951
952 252
        $this->entityStates[$oid] = self::STATE_MANAGED;
953
954 252
        $this->scheduleForInsert($entity);
955 252
    }
956
957
    /**
958
     * @param mixed[] $idValue
959
     */
960 60
    private function hasMissingIdsWhichAreForeignKeys(ClassMetadata $class, array $idValue) : bool
961
    {
962 60
        foreach ($idValue as $idField => $idFieldValue) {
963 60
            if ($idFieldValue === null && isset($class->associationMappings[$idField])) {
964 60
                return true;
965
            }
966
        }
967
968 60
        return false;
969
    }
970
971
    /**
972
     * INTERNAL:
973
     * Computes the changeset of an individual entity, independently of the
974
     * computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
975
     *
976
     * The passed entity must be a managed entity. If the entity already has a change set
977
     * because this method is invoked during a commit cycle then the change sets are added.
978
     * whereby changes detected in this method prevail.
979
     *
980
     * @ignore
981
     *
982
     * @param ClassMetadata $class  The class descriptor of the entity.
983
     * @param object        $entity The entity for which to (re)calculate the change set.
984
     *
985
     * @return void
986
     *
987
     * @throws ORMInvalidArgumentException If the passed entity is not MANAGED.
988
     */
989 5
    public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity)
990
    {
991 5
        $oid = spl_object_hash($entity);
992
993 5
        if ( ! isset($this->entityStates[$oid]) || $this->entityStates[$oid] != self::STATE_MANAGED) {
994
            throw ORMInvalidArgumentException::entityNotManaged($entity);
995
        }
996
997
        // skip if change tracking is "NOTIFY"
998 5
        if ($class->isChangeTrackingNotify()) {
999
            return;
1000
        }
1001
1002 5
        if ( ! $class->isInheritanceTypeNone()) {
1003
            $class = $this->em->getClassMetadata(get_class($entity));
1004
        }
1005
1006 5
        $actualData = [];
1007
1008 5
        foreach ($class->reflFields as $name => $refProp) {
1009 5
            if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity())
1010 5
                && ($name !== $class->versionField)
1011 5
                && ! $class->isCollectionValuedAssociation($name)) {
1012 5
                $actualData[$name] = $refProp->getValue($entity);
1013
            }
1014
        }
1015
1016 5
        if ( ! isset($this->originalEntityData[$oid])) {
1017
            throw new \RuntimeException('Cannot call recomputeSingleEntityChangeSet before computeChangeSet on an entity.');
1018
        }
1019
1020 5
        $originalData = $this->originalEntityData[$oid];
1021 5
        $changeSet = [];
1022
1023 5
        foreach ($actualData as $propName => $actualValue) {
1024 5
            $orgValue = $originalData[$propName] ?? null;
1025
1026 5
            if ($orgValue !== $actualValue) {
1027 5
                $changeSet[$propName] = [$orgValue, $actualValue];
1028
            }
1029
        }
1030
1031 5
        if ($changeSet) {
1032 3
            if (isset($this->entityChangeSets[$oid])) {
1033 3
                $this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
1034
            } else if ( ! isset($this->entityInsertions[$oid])) {
1035
                $this->entityChangeSets[$oid] = $changeSet;
1036
                $this->entityUpdates[$oid]    = $entity;
1037
            }
1038 3
            $this->originalEntityData[$oid] = $actualData;
1039
        }
1040 5
    }
1041
1042
    /**
1043
     * Executes all entity insertions for entities of the specified type.
1044
     *
1045
     * @param \Doctrine\ORM\Mapping\ClassMetadata $class
1046
     *
1047
     * @return void
1048
     */
1049 219
    private function executeInserts($class)
1050
    {
1051 219
        $entities   = [];
1052 219
        $className  = $class->name;
1053 219
        $persister  = $this->getEntityPersister($className);
1054 219
        $invoke     = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist);
1055
1056 219
        $insertionsForClass = [];
1057
1058 219
        foreach ($this->entityInsertions as $oid => $entity) {
1059
1060 219
            if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1061 75
                continue;
1062
            }
1063
1064 219
            $insertionsForClass[$oid] = $entity;
1065
1066 219
            $persister->addInsert($entity);
1067
1068 219
            unset($this->entityInsertions[$oid]);
1069
1070 219
            if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1071 219
                $entities[] = $entity;
1072
            }
1073
        }
1074
1075 219
        $postInsertIds = $persister->executeInserts();
1076
1077 219
        if ($postInsertIds) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $postInsertIds 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...
1078
            // Persister returned post-insert IDs
1079 166
            foreach ($postInsertIds as $postInsertId) {
1080 166
                $idField = $class->getSingleIdentifierFieldName();
1081 166
                $idValue = $this->convertSingleFieldIdentifierToPHPValue($class, $postInsertId['generatedId']);
1082
1083 166
                $entity  = $postInsertId['entity'];
1084 166
                $oid     = spl_object_hash($entity);
1085
1086 166
                $class->reflFields[$idField]->setValue($entity, $idValue);
1087
1088 166
                $this->entityIdentifiers[$oid] = [$idField => $idValue];
1089 166
                $this->entityStates[$oid] = self::STATE_MANAGED;
1090 166
                $this->originalEntityData[$oid][$idField] = $idValue;
1091
1092 166
                $this->addToIdentityMap($entity);
1093
            }
1094
        } else {
1095 62
            foreach ($insertionsForClass as $oid => $entity) {
1096 44
                if (! isset($this->entityIdentifiers[$oid])) {
1097
                    //entity was not added to identity map because some identifiers are foreign keys to new entities.
1098
                    //add it now
1099 44
                    $this->addToEntityIdentifiersAndEntityMap($class, $oid, $entity);
1100
                }
1101
            }
1102
        }
1103
1104 219
        foreach ($entities as $entity) {
1105 1
            $this->listenersInvoker->invoke($class, Events::postPersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
1106
        }
1107 219
    }
1108
1109
    /**
1110
     * @param object $entity
1111
     */
1112
    private function addToEntityIdentifiersAndEntityMap(ClassMetadata $class, string $oid, $entity): void
1113
    {
1114
        $identifier = [];
1115
1116
        foreach ($class->getIdentifierFieldNames() as $idField) {
1117
            $value = $class->getFieldValue($entity, $idField);
1118
1119
            if (isset($class->associationMappings[$idField])) {
1120
                // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced.
1121
                $value = $this->getSingleIdentifierValue($value);
1122
            }
1123
1124
            $identifier[$idField] = $this->originalEntityData[$oid][$idField] = $value;
1125
        }
1126
1127
        $this->entityStates[$oid]      = self::STATE_MANAGED;
1128
        $this->entityIdentifiers[$oid] = $identifier;
1129
1130
        $this->addToIdentityMap($entity);
1131
    }
1132
1133
    /**
1134
     * Executes all entity updates for entities of the specified type.
1135
     *
1136
     * @param \Doctrine\ORM\Mapping\ClassMetadata $class
1137
     *
1138
     * @return void
1139
     */
1140 45
    private function executeUpdates($class)
1141
    {
1142 45
        $className          = $class->name;
1143 45
        $persister          = $this->getEntityPersister($className);
1144 45
        $preUpdateInvoke    = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate);
1145 45
        $postUpdateInvoke   = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate);
1146
1147 45
        foreach ($this->entityUpdates as $oid => $entity) {
1148 45
            if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1149 8
                continue;
1150
            }
1151
1152 45
            if ($preUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
1153 4
                $this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->getEntityChangeSet($entity)), $preUpdateInvoke);
1154
1155 4
                $this->recomputeSingleEntityChangeSet($class, $entity);
1156
            }
1157
1158 45
            if ( ! empty($this->entityChangeSets[$oid])) {
1159 29
                $persister->update($entity);
1160
            }
1161
1162 41
            unset($this->entityUpdates[$oid]);
1163
1164 41
            if ($postUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
1165 41
                $this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke);
1166
            }
1167
        }
1168 41
    }
1169
1170
    /**
1171
     * Executes all entity deletions for entities of the specified type.
1172
     *
1173
     * @param \Doctrine\ORM\Mapping\ClassMetadata $class
1174
     *
1175
     * @return void
1176
     */
1177 17
    private function executeDeletions($class)
1178
    {
1179 17
        $className  = $class->name;
1180 17
        $persister  = $this->getEntityPersister($className);
1181 17
        $invoke     = $this->listenersInvoker->getSubscribedSystems($class, Events::postRemove);
1182
1183 17
        foreach ($this->entityDeletions as $oid => $entity) {
1184 17
            if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1185 4
                continue;
1186
            }
1187
1188 17
            $persister->delete($entity);
1189
1190
            unset(
1191 17
                $this->entityDeletions[$oid],
1192 17
                $this->entityIdentifiers[$oid],
1193 17
                $this->originalEntityData[$oid],
1194 17
                $this->entityStates[$oid]
1195
            );
1196
1197
            // Entity with this $oid after deletion treated as NEW, even if the $oid
1198
            // is obtained by a new entity because the old one went out of scope.
1199
            //$this->entityStates[$oid] = self::STATE_NEW;
1200 17
            if ( ! $class->isIdentifierNatural()) {
1201 15
                $class->reflFields[$class->identifier[0]]->setValue($entity, null);
1202
            }
1203
1204 17
            if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1205 17
                $this->listenersInvoker->invoke($class, Events::postRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
1206
            }
1207
        }
1208 16
    }
1209
1210
    /**
1211
     * Gets the commit order.
1212
     *
1213
     * @param array|null $entityChangeSet
1214
     *
1215
     * @return array
1216
     */
1217 223
    private function getCommitOrder(array $entityChangeSet = null)
1218
    {
1219 223
        if ($entityChangeSet === null) {
1220 223
            $entityChangeSet = array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions);
1221
        }
1222
1223 223
        $calc = $this->getCommitOrderCalculator();
1224
1225
        // See if there are any new classes in the changeset, that are not in the
1226
        // commit order graph yet (don't have a node).
1227
        // We have to inspect changeSet to be able to correctly build dependencies.
1228
        // It is not possible to use IdentityMap here because post inserted ids
1229
        // are not yet available.
1230 223
        $newNodes = [];
1231
1232 223
        foreach ($entityChangeSet as $entity) {
1233 223
            $class = $this->em->getClassMetadata(get_class($entity));
1234
1235 223
            if ($calc->hasNode($class->name)) {
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1236 84
                continue;
1237
            }
1238
1239 223
            $calc->addNode($class->name, $class);
1240
1241 223
            $newNodes[] = $class;
1242
        }
1243
1244
        // Calculate dependencies for new nodes
1245 223
        while ($class = array_pop($newNodes)) {
1246 223
            foreach ($class->associationMappings as $assoc) {
1247 75
                if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
1248 70
                    continue;
1249
                }
1250
1251 23
                $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
1252
1253 23
                if ( ! $calc->hasNode($targetClass->name)) {
1254 19
                    $calc->addNode($targetClass->name, $targetClass);
1255
1256 19
                    $newNodes[] = $targetClass;
1257
                }
1258
1259 23
                $joinColumns = reset($assoc['joinColumns']);
1260
1261 23
                $calc->addDependency($targetClass->name, $class->name, (int)empty($joinColumns['nullable']));
1262
1263
                // If the target class has mapped subclasses, these share the same dependency.
1264 23
                if ( ! $targetClass->subClasses) {
0 ignored issues
show
Bug introduced by
Accessing subClasses on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1265 23
                    continue;
1266
                }
1267
1268 3
                foreach ($targetClass->subClasses as $subClassName) {
1269 3
                    $targetSubClass = $this->em->getClassMetadata($subClassName);
1270
1271 3
                    if ( ! $calc->hasNode($subClassName)) {
1272 3
                        $calc->addNode($targetSubClass->name, $targetSubClass);
1273
1274 3
                        $newNodes[] = $targetSubClass;
1275
                    }
1276
1277 3
                    $calc->addDependency($targetSubClass->name, $class->name, 1);
1278
                }
1279
            }
1280
        }
1281
1282 223
        return $calc->sort();
1283
    }
1284
1285
    /**
1286
     * Schedules an entity for insertion into the database.
1287
     * If the entity already has an identifier, it will be added to the identity map.
1288
     *
1289
     * @param object $entity The entity to schedule for insertion.
1290
     *
1291
     * @return void
1292
     *
1293
     * @throws ORMInvalidArgumentException
1294
     * @throws \InvalidArgumentException
1295
     */
1296 253
    public function scheduleForInsert($entity)
1297
    {
1298 253
        $oid = spl_object_hash($entity);
1299
1300 253
        if (isset($this->entityUpdates[$oid])) {
1301
            throw new InvalidArgumentException("Dirty entity can not be scheduled for insertion.");
1302
        }
1303
1304 253
        if (isset($this->entityDeletions[$oid])) {
1305
            throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
1306
        }
1307 253
        if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
1308
            throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
1309
        }
1310
1311 253
        if (isset($this->entityInsertions[$oid])) {
1312 1
            throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
1313
        }
1314
1315 253
        $this->entityInsertions[$oid] = $entity;
1316
1317 253
        if (isset($this->entityIdentifiers[$oid])) {
1318 60
            $this->addToIdentityMap($entity);
1319
        }
1320
1321 253
        if ($entity instanceof NotifyPropertyChanged) {
1322 7
            $entity->addPropertyChangedListener($this);
1323
        }
1324 253
    }
1325
1326
    /**
1327
     * Checks whether an entity is scheduled for insertion.
1328
     *
1329
     * @param object $entity
1330
     *
1331
     * @return boolean
1332
     */
1333 10
    public function isScheduledForInsert($entity)
1334
    {
1335 10
        return isset($this->entityInsertions[spl_object_hash($entity)]);
1336
    }
1337
1338
    /**
1339
     * Schedules an entity for being updated.
1340
     *
1341
     * @param object $entity The entity to schedule for being updated.
1342
     *
1343
     * @return void
1344
     *
1345
     * @throws ORMInvalidArgumentException
1346
     */
1347 1
    public function scheduleForUpdate($entity)
1348
    {
1349 1
        $oid = spl_object_hash($entity);
1350
1351 1
        if ( ! isset($this->entityIdentifiers[$oid])) {
1352
            throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "scheduling for update");
1353
        }
1354
1355 1
        if (isset($this->entityDeletions[$oid])) {
1356
            throw ORMInvalidArgumentException::entityIsRemoved($entity, "schedule for update");
1357
        }
1358
1359 1
        if ( ! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
1360 1
            $this->entityUpdates[$oid] = $entity;
1361
        }
1362 1
    }
1363
1364
    /**
1365
     * INTERNAL:
1366
     * Schedules an extra update that will be executed immediately after the
1367
     * regular entity updates within the currently running commit cycle.
1368
     *
1369
     * Extra updates for entities are stored as (entity, changeset) tuples.
1370
     *
1371
     * @ignore
1372
     *
1373
     * @param object $entity    The entity for which to schedule an extra update.
1374
     * @param array  $changeset The changeset of the entity (what to update).
1375
     *
1376
     * @return void
1377
     */
1378
    public function scheduleExtraUpdate($entity, array $changeset)
1379
    {
1380
        $oid         = spl_object_hash($entity);
1381
        $extraUpdate = [$entity, $changeset];
1382
1383
        if (isset($this->extraUpdates[$oid])) {
1384
            list(, $changeset2) = $this->extraUpdates[$oid];
1385
1386
            $extraUpdate = [$entity, $changeset + $changeset2];
1387
        }
1388
1389
        $this->extraUpdates[$oid] = $extraUpdate;
1390
    }
1391
1392
    /**
1393
     * Checks whether an entity is registered as dirty in the unit of work.
1394
     * Note: Is not very useful currently as dirty entities are only registered
1395
     * at commit time.
1396
     *
1397
     * @param object $entity
1398
     *
1399
     * @return boolean
1400
     */
1401
    public function isScheduledForUpdate($entity)
1402
    {
1403
        return isset($this->entityUpdates[spl_object_hash($entity)]);
1404
    }
1405
1406
    /**
1407
     * Checks whether an entity is registered to be checked in the unit of work.
1408
     *
1409
     * @param object $entity
1410
     *
1411
     * @return boolean
1412
     */
1413 3
    public function isScheduledForDirtyCheck($entity)
1414
    {
1415 3
        $rootEntityName = $this->em->getClassMetadata(get_class($entity))->rootEntityName;
0 ignored issues
show
Bug introduced by
Accessing rootEntityName on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1416
1417 3
        return isset($this->scheduledForSynchronization[$rootEntityName][spl_object_hash($entity)]);
1418
    }
1419
1420
    /**
1421
     * INTERNAL:
1422
     * Schedules an entity for deletion.
1423
     *
1424
     * @param object $entity
1425
     *
1426
     * @return void
1427
     */
1428 20
    public function scheduleForDelete($entity)
1429
    {
1430 20
        $oid = spl_object_hash($entity);
1431
1432 20
        if (isset($this->entityInsertions[$oid])) {
1433 1
            if ($this->isInIdentityMap($entity)) {
1434
                $this->removeFromIdentityMap($entity);
1435
            }
1436
1437 1
            unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
1438
1439 1
            return; // entity has not been persisted yet, so nothing more to do.
1440
        }
1441
1442 19
        if ( ! $this->isInIdentityMap($entity)) {
1443 1
            return;
1444
        }
1445
1446 18
        $this->removeFromIdentityMap($entity);
1447
1448 18
        unset($this->entityUpdates[$oid]);
1449
1450 18
        if ( ! isset($this->entityDeletions[$oid])) {
1451 18
            $this->entityDeletions[$oid] = $entity;
1452 18
            $this->entityStates[$oid]    = self::STATE_REMOVED;
1453
        }
1454 18
    }
1455
1456
    /**
1457
     * Checks whether an entity is registered as removed/deleted with the unit
1458
     * of work.
1459
     *
1460
     * @param object $entity
1461
     *
1462
     * @return boolean
1463
     */
1464 2
    public function isScheduledForDelete($entity)
1465
    {
1466 2
        return isset($this->entityDeletions[spl_object_hash($entity)]);
1467
    }
1468
1469
    /**
1470
     * Checks whether an entity is scheduled for insertion, update or deletion.
1471
     *
1472
     * @param object $entity
1473
     *
1474
     * @return boolean
1475
     */
1476
    public function isEntityScheduled($entity)
1477
    {
1478
        $oid = spl_object_hash($entity);
1479
1480
        return isset($this->entityInsertions[$oid])
1481
            || isset($this->entityUpdates[$oid])
1482
            || isset($this->entityDeletions[$oid]);
1483
    }
1484
1485
    /**
1486
     * INTERNAL:
1487
     * Registers an entity in the identity map.
1488
     * Note that entities in a hierarchy are registered with the class name of
1489
     * the root entity.
1490
     *
1491
     * @ignore
1492
     *
1493
     * @param object $entity The entity to register.
1494
     *
1495
     * @return boolean TRUE if the registration was successful, FALSE if the identity of
1496
     *                 the entity in question is already managed.
1497
     *
1498
     * @throws ORMInvalidArgumentException
1499
     */
1500 309
    public function addToIdentityMap($entity)
1501
    {
1502 309
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1503 309
        $identifier    = $this->entityIdentifiers[spl_object_hash($entity)];
1504
1505 309
        if (empty($identifier) || in_array(null, $identifier, true)) {
1506 6
            throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->name, $entity);
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1507
        }
1508
1509 303
        $idHash    = implode(' ', $identifier);
1510 303
        $className = $classMetadata->rootEntityName;
0 ignored issues
show
Bug introduced by
Accessing rootEntityName on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1511
1512 303
        if (isset($this->identityMap[$className][$idHash])) {
1513 18
            return false;
1514
        }
1515
1516 303
        $this->identityMap[$className][$idHash] = $entity;
1517
1518 303
        return true;
1519
    }
1520
1521
    /**
1522
     * Gets the state of an entity with regard to the current unit of work.
1523
     *
1524
     * @param object   $entity
1525
     * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
1526
     *                         This parameter can be set to improve performance of entity state detection
1527
     *                         by potentially avoiding a database lookup if the distinction between NEW and DETACHED
1528
     *                         is either known or does not matter for the caller of the method.
1529
     *
1530
     * @return int The entity state.
1531
     */
1532 267
    public function getEntityState($entity, $assume = null)
1533
    {
1534 267
        $oid = spl_object_hash($entity);
1535
1536 267
        if (isset($this->entityStates[$oid])) {
1537 103
            return $this->entityStates[$oid];
1538
        }
1539
1540 261
        if ($assume !== null) {
1541 257
            return $assume;
1542
        }
1543
1544
        // State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
1545
        // Note that you can not remember the NEW or DETACHED state in _entityStates since
1546
        // the UoW does not hold references to such objects and the object hash can be reused.
1547
        // More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
1548 5
        $class = $this->em->getClassMetadata(get_class($entity));
1549 5
        $id    = $class->getIdentifierValues($entity);
1550
1551 5
        if ( ! $id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type 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...
1552 2
            return self::STATE_NEW;
1553
        }
1554
1555 3
        if ($class->containsForeignIdentifier) {
0 ignored issues
show
Bug introduced by
Accessing containsForeignIdentifier on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1556
            $id = $this->identifierFlattener->flattenIdentifier($class, $id);
1557
        }
1558
1559
        switch (true) {
1560 3
            case ($class->isIdentifierNatural()):
0 ignored issues
show
Bug introduced by
The method isIdentifierNatural() 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

1560
            case ($class->/** @scrutinizer ignore-call */ isIdentifierNatural()):

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...
1561
                // Check for a version field, if available, to avoid a db lookup.
1562 3
                if ($class->isVersioned) {
0 ignored issues
show
Bug introduced by
Accessing isVersioned on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1563 1
                    return ($class->getFieldValue($entity, $class->versionField))
0 ignored issues
show
Bug introduced by
Accessing versionField on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
Bug introduced by
The method getFieldValue() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. Did you maybe mean getFieldNames()? ( Ignorable by Annotation )

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

1563
                    return ($class->/** @scrutinizer ignore-call */ getFieldValue($entity, $class->versionField))

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...
1564
                        ? self::STATE_DETACHED
1565 1
                        : self::STATE_NEW;
1566
                }
1567
1568
                // Last try before db lookup: check the identity map.
1569 2
                if ($this->tryGetById($id, $class->rootEntityName)) {
0 ignored issues
show
Bug introduced by
Accessing rootEntityName on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1570 1
                    return self::STATE_DETACHED;
1571
                }
1572
1573
                // db lookup
1574 2
                if ($this->getEntityPersister($class->name)->exists($entity)) {
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1575
                    return self::STATE_DETACHED;
1576
                }
1577
1578 2
                return self::STATE_NEW;
1579
1580
            case ( ! $class->idGenerator->isPostInsertGenerator()):
0 ignored issues
show
Bug introduced by
Accessing idGenerator on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1581
                // if we have a pre insert generator we can't be sure that having an id
1582
                // really means that the entity exists. We have to verify this through
1583
                // the last resort: a db lookup
1584
1585
                // Last try before db lookup: check the identity map.
1586
                if ($this->tryGetById($id, $class->rootEntityName)) {
1587
                    return self::STATE_DETACHED;
1588
                }
1589
1590
                // db lookup
1591
                if ($this->getEntityPersister($class->name)->exists($entity)) {
1592
                    return self::STATE_DETACHED;
1593
                }
1594
1595
                return self::STATE_NEW;
1596
1597
            default:
1598
                return self::STATE_DETACHED;
1599
        }
1600
    }
1601
1602
    /**
1603
     * INTERNAL:
1604
     * Removes an entity from the identity map. This effectively detaches the
1605
     * entity from the persistence management of Doctrine.
1606
     *
1607
     * @ignore
1608
     *
1609
     * @param object $entity
1610
     *
1611
     * @return boolean
1612
     *
1613
     * @throws ORMInvalidArgumentException
1614
     */
1615 21
    public function removeFromIdentityMap($entity)
1616
    {
1617 21
        $oid           = spl_object_hash($entity);
1618 21
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1619 21
        $idHash        = implode(' ', $this->entityIdentifiers[$oid]);
1620
1621 21
        if ($idHash === '') {
1622
            throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "remove from identity map");
1623
        }
1624
1625 21
        $className = $classMetadata->rootEntityName;
0 ignored issues
show
Bug introduced by
Accessing rootEntityName on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1626
1627 21
        if (isset($this->identityMap[$className][$idHash])) {
1628 21
            unset($this->identityMap[$className][$idHash]);
1629 21
            unset($this->readOnlyObjects[$oid]);
1630
1631
            //$this->entityStates[$oid] = self::STATE_DETACHED;
1632
1633 21
            return true;
1634
        }
1635
1636
        return false;
1637
    }
1638
1639
    /**
1640
     * INTERNAL:
1641
     * Gets an entity in the identity map by its identifier hash.
1642
     *
1643
     * @ignore
1644
     *
1645
     * @param string $idHash
1646
     * @param string $rootClassName
1647
     *
1648
     * @return object
1649
     */
1650 6
    public function getByIdHash($idHash, $rootClassName)
1651
    {
1652 6
        return $this->identityMap[$rootClassName][$idHash];
1653
    }
1654
1655
    /**
1656
     * INTERNAL:
1657
     * Tries to get an entity by its identifier hash. If no entity is found for
1658
     * the given hash, FALSE is returned.
1659
     *
1660
     * @ignore
1661
     *
1662
     * @param mixed  $idHash        (must be possible to cast it to string)
1663
     * @param string $rootClassName
1664
     *
1665
     * @return object|bool The found entity or FALSE.
1666
     */
1667
    public function tryGetByIdHash($idHash, $rootClassName)
1668
    {
1669
        $stringIdHash = (string) $idHash;
1670
1671
        return isset($this->identityMap[$rootClassName][$stringIdHash])
1672
            ? $this->identityMap[$rootClassName][$stringIdHash]
1673
            : false;
1674
    }
1675
1676
    /**
1677
     * Checks whether an entity is registered in the identity map of this UnitOfWork.
1678
     *
1679
     * @param object $entity
1680
     *
1681
     * @return boolean
1682
     */
1683 40
    public function isInIdentityMap($entity)
1684
    {
1685 40
        $oid = spl_object_hash($entity);
1686
1687 40
        if (empty($this->entityIdentifiers[$oid])) {
1688 14
            return false;
1689
        }
1690
1691 28
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1692 28
        $idHash        = implode(' ', $this->entityIdentifiers[$oid]);
1693
1694 28
        return isset($this->identityMap[$classMetadata->rootEntityName][$idHash]);
0 ignored issues
show
Bug introduced by
Accessing rootEntityName on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1695
    }
1696
1697
    /**
1698
     * INTERNAL:
1699
     * Checks whether an identifier hash exists in the identity map.
1700
     *
1701
     * @ignore
1702
     *
1703
     * @param string $idHash
1704
     * @param string $rootClassName
1705
     *
1706
     * @return boolean
1707
     */
1708
    public function containsIdHash($idHash, $rootClassName)
1709
    {
1710
        return isset($this->identityMap[$rootClassName][$idHash]);
1711
    }
1712
1713
    /**
1714
     * Persists an entity as part of the current unit of work.
1715
     *
1716
     * @param object $entity The entity to persist.
1717
     *
1718
     * @return void
1719
     */
1720 248
    public function persist($entity)
1721
    {
1722 248
        $visited = [];
1723
1724 248
        $this->doPersist($entity, $visited);
1725 241
    }
1726
1727
    /**
1728
     * Persists an entity as part of the current unit of work.
1729
     *
1730
     * This method is internally called during persist() cascades as it tracks
1731
     * the already visited entities to prevent infinite recursions.
1732
     *
1733
     * @param object $entity  The entity to persist.
1734
     * @param array  $visited The already visited entities.
1735
     *
1736
     * @return void
1737
     *
1738
     * @throws ORMInvalidArgumentException
1739
     * @throws UnexpectedValueException
1740
     */
1741 248
    private function doPersist($entity, array &$visited)
1742
    {
1743 248
        $oid = spl_object_hash($entity);
1744
1745 248
        if (isset($visited[$oid])) {
1746 3
            return; // Prevent infinite recursion
1747
        }
1748
1749 248
        $visited[$oid] = $entity; // Mark visited
1750
1751 248
        $class = $this->em->getClassMetadata(get_class($entity));
1752
1753
        // We assume NEW, so DETACHED entities result in an exception on flush (constraint violation).
1754
        // If we would detect DETACHED here we would throw an exception anyway with the same
1755
        // consequences (not recoverable/programming error), so just assuming NEW here
1756
        // lets us avoid some database lookups for entities with natural identifiers.
1757 248
        $entityState = $this->getEntityState($entity, self::STATE_NEW);
1758
1759
        switch ($entityState) {
1760 248
            case self::STATE_MANAGED:
1761
                // Nothing to do, except if policy is "deferred explicit"
1762 24
                if ($class->isChangeTrackingDeferredExplicit()) {
1763 3
                    $this->scheduleForDirtyCheck($entity);
1764
                }
1765 24
                break;
1766
1767 248
            case self::STATE_NEW:
1768 247
                $this->persistNew($class, $entity);
1769 247
                break;
1770
1771 1
            case self::STATE_REMOVED:
1772
                // Entity becomes managed again
1773 1
                unset($this->entityDeletions[$oid]);
1774 1
                $this->addToIdentityMap($entity);
1775
1776 1
                $this->entityStates[$oid] = self::STATE_MANAGED;
1777 1
                break;
1778
1779
            case self::STATE_DETACHED:
1780
                // Can actually not happen right now since we assume STATE_NEW.
1781
                throw ORMInvalidArgumentException::detachedEntityCannot($entity, "persisted");
1782
1783
            default:
1784
                throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
1785
        }
1786
1787 248
        $this->cascadePersist($entity, $visited);
1788 241
    }
1789
1790
    /**
1791
     * Deletes an entity as part of the current unit of work.
1792
     *
1793
     * @param object $entity The entity to remove.
1794
     *
1795
     * @return void
1796
     */
1797 19
    public function remove($entity)
1798
    {
1799 19
        $visited = [];
1800
1801 19
        $this->doRemove($entity, $visited);
1802 19
    }
1803
1804
    /**
1805
     * Deletes an entity as part of the current unit of work.
1806
     *
1807
     * This method is internally called during delete() cascades as it tracks
1808
     * the already visited entities to prevent infinite recursions.
1809
     *
1810
     * @param object $entity  The entity to delete.
1811
     * @param array  $visited The map of the already visited entities.
1812
     *
1813
     * @return void
1814
     *
1815
     * @throws ORMInvalidArgumentException If the instance is a detached entity.
1816
     * @throws UnexpectedValueException
1817
     */
1818 19
    private function doRemove($entity, array &$visited)
1819
    {
1820 19
        $oid = spl_object_hash($entity);
1821
1822 19
        if (isset($visited[$oid])) {
1823
            return; // Prevent infinite recursion
1824
        }
1825
1826 19
        $visited[$oid] = $entity; // mark visited
1827
1828
        // Cascade first, because scheduleForDelete() removes the entity from the identity map, which
1829
        // can cause problems when a lazy proxy has to be initialized for the cascade operation.
1830 19
        $this->cascadeRemove($entity, $visited);
1831
1832 19
        $class       = $this->em->getClassMetadata(get_class($entity));
1833 19
        $entityState = $this->getEntityState($entity);
1834
1835
        switch ($entityState) {
1836 19
            case self::STATE_NEW:
1837 19
            case self::STATE_REMOVED:
1838
                // nothing to do
1839
                break;
1840
1841 19
            case self::STATE_MANAGED:
1842 19
                $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preRemove);
1843
1844 19
                if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1845 1
                    $this->listenersInvoker->invoke($class, Events::preRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
1846
                }
1847
1848 19
                $this->scheduleForDelete($entity);
1849 19
                break;
1850
1851
            case self::STATE_DETACHED:
1852
                throw ORMInvalidArgumentException::detachedEntityCannot($entity, "removed");
1853
            default:
1854
                throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
1855
        }
1856
1857 19
    }
1858
1859
    /**
1860
     * Merges the state of the given detached entity into this UnitOfWork.
1861
     *
1862
     * @param object $entity
1863
     *
1864
     * @return object The managed copy of the entity.
1865
     *
1866
     * @throws OptimisticLockException If the entity uses optimistic locking through a version
1867
     *         attribute and the version check against the managed copy fails.
1868
     *
1869
     * @todo Require active transaction!? OptimisticLockException may result in undefined state!?
1870
     */
1871 22
    public function merge($entity)
1872
    {
1873 22
        $visited = [];
1874
1875 22
        return $this->doMerge($entity, $visited);
1876
    }
1877
1878
    /**
1879
     * Executes a merge operation on an entity.
1880
     *
1881
     * @param object      $entity
1882
     * @param array       $visited
1883
     * @param object|null $prevManagedCopy
1884
     * @param array|null  $assoc
1885
     *
1886
     * @return object The managed copy of the entity.
1887
     *
1888
     * @throws OptimisticLockException If the entity uses optimistic locking through a version
1889
     *         attribute and the version check against the managed copy fails.
1890
     * @throws ORMInvalidArgumentException If the entity instance is NEW.
1891
     * @throws EntityNotFoundException if an assigned identifier is used in the entity, but none is provided
1892
     */
1893 22
    private function doMerge($entity, array &$visited, $prevManagedCopy = null, array $assoc = [])
1894
    {
1895 22
        $oid = spl_object_hash($entity);
1896
1897 22
        if (isset($visited[$oid])) {
1898 1
            $managedCopy = $visited[$oid];
1899
1900 1
            if ($prevManagedCopy !== null) {
1901 1
                $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, $managedCopy);
1902
            }
1903
1904 1
            return $managedCopy;
1905
        }
1906
1907 22
        $class = $this->em->getClassMetadata(get_class($entity));
1908
1909
        // First we assume DETACHED, although it can still be NEW but we can avoid
1910
        // an extra db-roundtrip this way. If it is not MANAGED but has an identity,
1911
        // we need to fetch it from the db anyway in order to merge.
1912
        // MANAGED entities are ignored by the merge operation.
1913 22
        $managedCopy = $entity;
1914
1915 22
        if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) {
1916
            // Try to look the entity up in the identity map.
1917 21
            $id = $class->getIdentifierValues($entity);
1918
1919
            // If there is no ID, it is actually NEW.
1920 21
            if ( ! $id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type 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...
1921 4
                $managedCopy = $this->newInstance($class);
1922
1923 4
                $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy);
1924 4
                $this->persistNew($class, $managedCopy);
1925
            } else {
1926 17
                $flatId = ($class->containsForeignIdentifier)
0 ignored issues
show
Bug introduced by
Accessing containsForeignIdentifier on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1927 2
                    ? $this->identifierFlattener->flattenIdentifier($class, $id)
1928 17
                    : $id;
1929
1930 17
                $managedCopy = $this->tryGetById($flatId, $class->rootEntityName);
0 ignored issues
show
Bug introduced by
Accessing rootEntityName on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1931
1932 17
                if ($managedCopy) {
1933
                    // We have the entity in-memory already, just make sure its not removed.
1934 7
                    if ($this->getEntityState($managedCopy) == self::STATE_REMOVED) {
0 ignored issues
show
Bug introduced by
It seems like $managedCopy can also be of type true; however, parameter $entity of Doctrine\ORM\UnitOfWork::getEntityState() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

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

1934
                    if ($this->getEntityState(/** @scrutinizer ignore-type */ $managedCopy) == self::STATE_REMOVED) {
Loading history...
1935 7
                        throw ORMInvalidArgumentException::entityIsRemoved($managedCopy, "merge");
0 ignored issues
show
Bug introduced by
It seems like $managedCopy can also be of type true; however, parameter $entity of Doctrine\ORM\ORMInvalidA...tion::entityIsRemoved() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

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

1935
                        throw ORMInvalidArgumentException::entityIsRemoved(/** @scrutinizer ignore-type */ $managedCopy, "merge");
Loading history...
1936
                    }
1937
                } else {
1938
                    // We need to fetch the managed copy in order to merge.
1939 10
                    $managedCopy = $this->em->find($class->name, $flatId);
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1940
                }
1941
1942 17
                if ($managedCopy === null) {
1943
                    // If the identifier is ASSIGNED, it is NEW, otherwise an error
1944
                    // since the managed entity was not found.
1945 3
                    if ( ! $class->isIdentifierNatural()) {
1946 1
                        throw EntityNotFoundException::fromClassNameAndIdentifier(
1947 1
                            $class->getName(),
1948 1
                            $this->identifierFlattener->flattenIdentifier($class, $id)
1949
                        );
1950
                    }
1951
1952 2
                    $managedCopy = $this->newInstance($class);
1953 2
                    $class->setIdentifierValues($managedCopy, $id);
1954
1955 2
                    $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy);
1956 2
                    $this->persistNew($class, $managedCopy);
1957
                } else {
1958 14
                    $this->ensureVersionMatch($class, $entity, $managedCopy);
0 ignored issues
show
Bug introduced by
It seems like $managedCopy can also be of type true; however, parameter $managedCopy of Doctrine\ORM\UnitOfWork::ensureVersionMatch() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

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

1958
                    $this->ensureVersionMatch($class, $entity, /** @scrutinizer ignore-type */ $managedCopy);
Loading history...
1959 14
                    $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy);
0 ignored issues
show
Bug introduced by
It seems like $managedCopy can also be of type true; however, parameter $managedCopy of Doctrine\ORM\UnitOfWork:...yStateIntoManagedCopy() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

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

1959
                    $this->mergeEntityStateIntoManagedCopy($entity, /** @scrutinizer ignore-type */ $managedCopy);
Loading history...
1960
                }
1961
            }
1962
1963 20
            $visited[$oid] = $managedCopy; // mark visited
1964
1965 20
            if ($class->isChangeTrackingDeferredExplicit()) {
1966
                $this->scheduleForDirtyCheck($entity);
1967
            }
1968
        }
1969
1970 21
        if ($prevManagedCopy !== null) {
1971 2
            $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, $managedCopy);
0 ignored issues
show
Bug introduced by
It seems like $managedCopy can also be of type true; however, parameter $managedCopy of Doctrine\ORM\UnitOfWork:...ationWithMergedEntity() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

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

1971
            $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, /** @scrutinizer ignore-type */ $managedCopy);
Loading history...
1972
        }
1973
1974
        // Mark the managed copy visited as well
1975 21
        $visited[spl_object_hash($managedCopy)] = $managedCopy;
0 ignored issues
show
Bug introduced by
It seems like $managedCopy can also be of type true; however, parameter $obj of spl_object_hash() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

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

1975
        $visited[spl_object_hash(/** @scrutinizer ignore-type */ $managedCopy)] = $managedCopy;
Loading history...
1976
1977 21
        $this->cascadeMerge($entity, $managedCopy, $visited);
0 ignored issues
show
Bug introduced by
It seems like $managedCopy can also be of type true; however, parameter $managedCopy of Doctrine\ORM\UnitOfWork::cascadeMerge() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

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

1977
        $this->cascadeMerge($entity, /** @scrutinizer ignore-type */ $managedCopy, $visited);
Loading history...
1978
1979 21
        return $managedCopy;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $managedCopy also could return the type true which is incompatible with the documented return type object.
Loading history...
1980
    }
1981
1982
    /**
1983
     * @param ClassMetadata $class
1984
     * @param object        $entity
1985
     * @param object        $managedCopy
1986
     *
1987
     * @return void
1988
     *
1989
     * @throws OptimisticLockException
1990
     */
1991 14
    private function ensureVersionMatch(ClassMetadata $class, $entity, $managedCopy)
1992
    {
1993 14
        if (! ($class->isVersioned && $this->isLoaded($managedCopy) && $this->isLoaded($entity))) {
1994 14
            return;
1995
        }
1996
1997
        $reflField          = $class->reflFields[$class->versionField];
1998
        $managedCopyVersion = $reflField->getValue($managedCopy);
1999
        $entityVersion      = $reflField->getValue($entity);
2000
2001
        // Throw exception if versions don't match.
2002
        if ($managedCopyVersion == $entityVersion) {
2003
            return;
2004
        }
2005
2006
        throw OptimisticLockException::lockFailedVersionMismatch($entity, $entityVersion, $managedCopyVersion);
2007
    }
2008
2009
    /**
2010
     * Tests if an entity is loaded - must either be a loaded proxy or not a proxy
2011
     *
2012
     * @param object $entity
2013
     *
2014
     * @return bool
2015
     */
2016 20
    private function isLoaded($entity)
2017
    {
2018 20
        return !($entity instanceof Proxy) || $entity->__isInitialized();
2019
    }
2020
2021
    /**
2022
     * Sets/adds associated managed copies into the previous entity's association field
2023
     *
2024
     * @param object $entity
2025
     * @param array  $association
2026
     * @param object $previousManagedCopy
2027
     * @param object $managedCopy
2028
     *
2029
     * @return void
2030
     */
2031 2
    private function updateAssociationWithMergedEntity($entity, array $association, $previousManagedCopy, $managedCopy)
2032
    {
2033 2
        $assocField = $association['fieldName'];
2034 2
        $prevClass  = $this->em->getClassMetadata(get_class($previousManagedCopy));
2035
2036 2
        if ($association['type'] & ClassMetadata::TO_ONE) {
2037 2
            $prevClass->reflFields[$assocField]->setValue($previousManagedCopy, $managedCopy);
0 ignored issues
show
Bug introduced by
Accessing reflFields on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2038
2039 2
            return;
2040
        }
2041
2042
        $value   = $prevClass->reflFields[$assocField]->getValue($previousManagedCopy);
2043
        $value[] = $managedCopy;
2044
2045
        if ($association['type'] == ClassMetadata::ONE_TO_MANY) {
2046
            $class = $this->em->getClassMetadata(get_class($entity));
2047
2048
            $class->reflFields[$association['mappedBy']]->setValue($managedCopy, $previousManagedCopy);
2049
        }
2050
    }
2051
2052
    /**
2053
     * Detaches an entity from the persistence management. It's persistence will
2054
     * no longer be managed by Doctrine.
2055
     *
2056
     * @param object $entity The entity to detach.
2057
     *
2058
     * @return void
2059
     */
2060 3
    public function detach($entity)
2061
    {
2062 3
        $visited = [];
2063
2064 3
        $this->doDetach($entity, $visited);
2065 3
    }
2066
2067
    /**
2068
     * Executes a detach operation on the given entity.
2069
     *
2070
     * @param object  $entity
2071
     * @param array   $visited
2072
     * @param boolean $noCascade if true, don't cascade detach operation.
2073
     *
2074
     * @return void
2075
     */
2076 6
    private function doDetach($entity, array &$visited, $noCascade = false)
2077
    {
2078 6
        $oid = spl_object_hash($entity);
2079
2080 6
        if (isset($visited[$oid])) {
2081
            return; // Prevent infinite recursion
2082
        }
2083
2084 6
        $visited[$oid] = $entity; // mark visited
2085
2086 6
        switch ($this->getEntityState($entity, self::STATE_DETACHED)) {
2087 6
            case self::STATE_MANAGED:
2088 4
                if ($this->isInIdentityMap($entity)) {
2089 3
                    $this->removeFromIdentityMap($entity);
2090
                }
2091
2092
                unset(
2093 4
                    $this->entityInsertions[$oid],
2094 4
                    $this->entityUpdates[$oid],
2095 4
                    $this->entityDeletions[$oid],
2096 4
                    $this->entityIdentifiers[$oid],
2097 4
                    $this->entityStates[$oid],
2098 4
                    $this->originalEntityData[$oid]
2099
                );
2100 4
                break;
2101 2
            case self::STATE_NEW:
2102 2
            case self::STATE_DETACHED:
2103 2
                return;
2104
        }
2105
2106 4
        if ( ! $noCascade) {
2107 4
            $this->cascadeDetach($entity, $visited);
2108
        }
2109 4
    }
2110
2111
    /**
2112
     * Refreshes the state of the given entity from the database, overwriting
2113
     * any local, unpersisted changes.
2114
     *
2115
     * @param object $entity The entity to refresh.
2116
     *
2117
     * @return void
2118
     *
2119
     * @throws InvalidArgumentException If the entity is not MANAGED.
2120
     */
2121 3
    public function refresh($entity)
2122
    {
2123 3
        $visited = [];
2124
2125 3
        $this->doRefresh($entity, $visited);
2126 3
    }
2127
2128
    /**
2129
     * Executes a refresh operation on an entity.
2130
     *
2131
     * @param object $entity  The entity to refresh.
2132
     * @param array  $visited The already visited entities during cascades.
2133
     *
2134
     * @return void
2135
     *
2136
     * @throws ORMInvalidArgumentException If the entity is not MANAGED.
2137
     */
2138 3
    private function doRefresh($entity, array &$visited)
2139
    {
2140 3
        $oid = spl_object_hash($entity);
2141
2142 3
        if (isset($visited[$oid])) {
2143
            return; // Prevent infinite recursion
2144
        }
2145
2146 3
        $visited[$oid] = $entity; // mark visited
2147
2148 3
        $class = $this->em->getClassMetadata(get_class($entity));
2149
2150 3
        if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
2151
            throw ORMInvalidArgumentException::entityNotManaged($entity);
2152
        }
2153
2154 3
        $this->getEntityPersister($class->name)->refresh(
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2155 3
            array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
0 ignored issues
show
Bug introduced by
It seems like array_combine($class->ge...ntityIdentifiers[$oid]) can also be of type false; however, parameter $id of Doctrine\ORM\Persisters\...ityPersister::refresh() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

2155
            /** @scrutinizer ignore-type */ array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
Loading history...
2156 3
            $entity
2157
        );
2158
2159 3
        $this->cascadeRefresh($entity, $visited);
2160 3
    }
2161
2162
    /**
2163
     * Cascades a refresh operation to associated entities.
2164
     *
2165
     * @param object $entity
2166
     * @param array  $visited
2167
     *
2168
     * @return void
2169
     */
2170 3
    private function cascadeRefresh($entity, array &$visited)
2171
    {
2172 3
        $class = $this->em->getClassMetadata(get_class($entity));
2173
2174 3
        $associationMappings = array_filter(
2175 3
            $class->associationMappings,
0 ignored issues
show
Bug introduced by
Accessing associationMappings on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2176
            function ($assoc) { return $assoc['isCascadeRefresh']; }
2177
        );
2178
2179 3
        foreach ($associationMappings as $assoc) {
2180
            $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
0 ignored issues
show
Bug introduced by
Accessing reflFields on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2181
2182
            switch (true) {
2183
                case ($relatedEntities instanceof PersistentCollection):
2184
                    // Unwrap so that foreach() does not initialize
2185
                    $relatedEntities = $relatedEntities->unwrap();
2186
                    // break; is commented intentionally!
2187
2188
                case ($relatedEntities instanceof Collection):
2189
                case (is_array($relatedEntities)):
2190
                    foreach ($relatedEntities as $relatedEntity) {
2191
                        $this->doRefresh($relatedEntity, $visited);
2192
                    }
2193
                    break;
2194
2195
                case ($relatedEntities !== null):
2196
                    $this->doRefresh($relatedEntities, $visited);
2197
                    break;
2198
2199
                default:
2200
                    // Do nothing
2201
            }
2202
        }
2203 3
    }
2204
2205
    /**
2206
     * Cascades a detach operation to associated entities.
2207
     *
2208
     * @param object $entity
2209
     * @param array  $visited
2210
     *
2211
     * @return void
2212
     */
2213 4
    private function cascadeDetach($entity, array &$visited)
2214
    {
2215 4
        $class = $this->em->getClassMetadata(get_class($entity));
2216
2217 4
        $associationMappings = array_filter(
2218 4
            $class->associationMappings,
0 ignored issues
show
Bug introduced by
Accessing associationMappings on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2219
            function ($assoc) { return $assoc['isCascadeDetach']; }
2220
        );
2221
2222 4
        foreach ($associationMappings as $assoc) {
2223 1
            $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
0 ignored issues
show
Bug introduced by
Accessing reflFields on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2224
2225
            switch (true) {
2226 1
                case ($relatedEntities instanceof PersistentCollection):
2227
                    // Unwrap so that foreach() does not initialize
2228
                    $relatedEntities = $relatedEntities->unwrap();
2229
                    // break; is commented intentionally!
2230
2231 1
                case ($relatedEntities instanceof Collection):
2232
                case (is_array($relatedEntities)):
2233 1
                    foreach ($relatedEntities as $relatedEntity) {
2234
                        $this->doDetach($relatedEntity, $visited);
2235
                    }
2236 1
                    break;
2237
2238
                case ($relatedEntities !== null):
2239
                    $this->doDetach($relatedEntities, $visited);
2240
                    break;
2241
2242 1
                default:
2243
                    // Do nothing
2244
            }
2245
        }
2246 4
    }
2247
2248
    /**
2249
     * Cascades a merge operation to associated entities.
2250
     *
2251
     * @param object $entity
2252
     * @param object $managedCopy
2253
     * @param array  $visited
2254
     *
2255
     * @return void
2256
     */
2257 21
    private function cascadeMerge($entity, $managedCopy, array &$visited)
2258
    {
2259 21
        $class = $this->em->getClassMetadata(get_class($entity));
2260
2261 21
        $associationMappings = array_filter(
2262 21
            $class->associationMappings,
0 ignored issues
show
Bug introduced by
Accessing associationMappings 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
            function ($assoc) { return $assoc['isCascadeMerge']; }
2264
        );
2265
2266 21
        foreach ($associationMappings as $assoc) {
2267 5
            $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
0 ignored issues
show
Bug introduced by
Accessing reflFields on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2268
2269 5
            if ($relatedEntities instanceof Collection) {
2270 3
                if ($relatedEntities === $class->reflFields[$assoc['fieldName']]->getValue($managedCopy)) {
2271
                    continue;
2272
                }
2273
2274 3
                if ($relatedEntities instanceof PersistentCollection) {
2275
                    // Unwrap so that foreach() does not initialize
2276
                    $relatedEntities = $relatedEntities->unwrap();
2277
                }
2278
2279 3
                foreach ($relatedEntities as $relatedEntity) {
2280 3
                    $this->doMerge($relatedEntity, $visited, $managedCopy, $assoc);
2281
                }
2282 2
            } else if ($relatedEntities !== null) {
2283 5
                $this->doMerge($relatedEntities, $visited, $managedCopy, $assoc);
2284
            }
2285
        }
2286 21
    }
2287
2288
    /**
2289
     * Cascades the save operation to associated entities.
2290
     *
2291
     * @param object $entity
2292
     * @param array  $visited
2293
     *
2294
     * @return void
2295
     */
2296 248
    private function cascadePersist($entity, array &$visited)
2297
    {
2298 248
        $class = $this->em->getClassMetadata(get_class($entity));
2299
2300 248
        $associationMappings = array_filter(
2301 248
            $class->associationMappings,
0 ignored issues
show
Bug introduced by
Accessing associationMappings on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2302
            function ($assoc) { return $assoc['isCascadePersist']; }
2303
        );
2304
2305 248
        foreach ($associationMappings as $assoc) {
2306 49
            $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
0 ignored issues
show
Bug introduced by
Accessing reflFields on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2307
2308
            switch (true) {
2309 49
                case ($relatedEntities instanceof PersistentCollection):
2310
                    // Unwrap so that foreach() does not initialize
2311 1
                    $relatedEntities = $relatedEntities->unwrap();
2312
                    // break; is commented intentionally!
2313
2314 49
                case ($relatedEntities instanceof Collection):
2315 37
                case (is_array($relatedEntities)):
2316 30
                    if (($assoc['type'] & ClassMetadata::TO_MANY) <= 0) {
2317 3
                        throw ORMInvalidArgumentException::invalidAssociation(
2318 3
                            $this->em->getClassMetadata($assoc['targetEntity']),
2319 3
                            $assoc,
2320 3
                            $relatedEntities
2321
                        );
2322
                    }
2323
2324 27
                    foreach ($relatedEntities as $relatedEntity) {
2325 15
                        $this->doPersist($relatedEntity, $visited);
2326
                    }
2327
2328 27
                    break;
2329
2330 30
                case ($relatedEntities !== null):
2331 9
                    if (! $relatedEntities instanceof $assoc['targetEntity']) {
2332 4
                        throw ORMInvalidArgumentException::invalidAssociation(
2333 4
                            $this->em->getClassMetadata($assoc['targetEntity']),
2334 4
                            $assoc,
2335 4
                            $relatedEntities
2336
                        );
2337
                    }
2338
2339 5
                    $this->doPersist($relatedEntities, $visited);
2340 5
                    break;
2341
2342 43
                default:
2343
                    // Do nothing
2344
            }
2345
        }
2346 241
    }
2347
2348
    /**
2349
     * Cascades the delete operation to associated entities.
2350
     *
2351
     * @param object $entity
2352
     * @param array  $visited
2353
     *
2354
     * @return void
2355
     */
2356 19
    private function cascadeRemove($entity, array &$visited)
2357
    {
2358 19
        $class = $this->em->getClassMetadata(get_class($entity));
2359
2360 19
        $associationMappings = array_filter(
2361 19
            $class->associationMappings,
0 ignored issues
show
Bug introduced by
Accessing associationMappings on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2362
            function ($assoc) { return $assoc['isCascadeRemove']; }
2363
        );
2364
2365 19
        $entitiesToCascade = [];
2366
2367 19
        foreach ($associationMappings as $assoc) {
2368 1
            if ($entity instanceof Proxy && !$entity->__isInitialized__) {
0 ignored issues
show
Bug introduced by
Accessing __isInitialized__ on the interface Doctrine\ORM\Proxy\Proxy suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2369
                $entity->__load();
2370
            }
2371
2372 1
            $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
0 ignored issues
show
Bug introduced by
Accessing reflFields on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2373
2374
            switch (true) {
2375 1
                case ($relatedEntities instanceof Collection):
2376 1
                case (is_array($relatedEntities)):
2377
                    // If its a PersistentCollection initialization is intended! No unwrap!
2378 1
                    foreach ($relatedEntities as $relatedEntity) {
2379
                        $entitiesToCascade[] = $relatedEntity;
2380
                    }
2381 1
                    break;
2382
2383 1
                case ($relatedEntities !== null):
2384
                    $entitiesToCascade[] = $relatedEntities;
2385
                    break;
2386
2387 1
                default:
2388
                    // Do nothing
2389
            }
2390
        }
2391
2392 19
        foreach ($entitiesToCascade as $relatedEntity) {
2393
            $this->doRemove($relatedEntity, $visited);
2394
        }
2395 19
    }
2396
2397
    /**
2398
     * Acquire a lock on the given entity.
2399
     *
2400
     * @param object $entity
2401
     * @param int    $lockMode
2402
     * @param int    $lockVersion
2403
     *
2404
     * @return void
2405
     *
2406
     * @throws ORMInvalidArgumentException
2407
     * @throws TransactionRequiredException
2408
     * @throws OptimisticLockException
2409
     */
2410 5
    public function lock($entity, $lockMode, $lockVersion = null)
2411
    {
2412 5
        if ($entity === null) {
2413 1
            throw new \InvalidArgumentException("No entity passed to UnitOfWork#lock().");
2414
        }
2415
2416 4
        if ($this->getEntityState($entity, self::STATE_DETACHED) != self::STATE_MANAGED) {
2417 1
            throw ORMInvalidArgumentException::entityNotManaged($entity);
2418
        }
2419
2420 3
        $class = $this->em->getClassMetadata(get_class($entity));
2421
2422
        switch (true) {
2423 3
            case LockMode::OPTIMISTIC === $lockMode:
2424 3
                if ( ! $class->isVersioned) {
0 ignored issues
show
Bug introduced by
Accessing isVersioned on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2425
                    throw OptimisticLockException::notVersioned($class->name);
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2426
                }
2427
2428 3
                if ($lockVersion === null) {
2429 1
                    return;
2430
                }
2431
2432 2
                if ($entity instanceof Proxy && !$entity->__isInitialized__) {
0 ignored issues
show
Bug introduced by
Accessing __isInitialized__ on the interface Doctrine\ORM\Proxy\Proxy suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2433 1
                    $entity->__load();
2434
                }
2435
2436 2
                $entityVersion = $class->reflFields[$class->versionField]->getValue($entity);
0 ignored issues
show
Bug introduced by
Accessing versionField on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
Bug introduced by
Accessing reflFields on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2437
2438 2
                if ($entityVersion != $lockVersion) {
2439 1
                    throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion);
2440
                }
2441
2442 1
                break;
2443
2444
            case LockMode::NONE === $lockMode:
2445
            case LockMode::PESSIMISTIC_READ === $lockMode:
2446
            case LockMode::PESSIMISTIC_WRITE === $lockMode:
2447
                if (!$this->em->getConnection()->isTransactionActive()) {
2448
                    throw TransactionRequiredException::transactionRequired();
2449
                }
2450
2451
                $oid = spl_object_hash($entity);
2452
2453
                $this->getEntityPersister($class->name)->lock(
2454
                    array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
0 ignored issues
show
Bug introduced by
It seems like array_combine($class->ge...ntityIdentifiers[$oid]) can also be of type false; however, parameter $criteria of Doctrine\ORM\Persisters\...EntityPersister::lock() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

2454
                    /** @scrutinizer ignore-type */ array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
Loading history...
2455
                    $lockMode
2456
                );
2457
                break;
2458
2459
            default:
2460
                // Do nothing
2461
        }
2462 1
    }
2463
2464
    /**
2465
     * Gets the CommitOrderCalculator used by the UnitOfWork to order commits.
2466
     *
2467
     * @return \Doctrine\ORM\Internal\CommitOrderCalculator
2468
     */
2469 223
    public function getCommitOrderCalculator()
2470
    {
2471 223
        return new Internal\CommitOrderCalculator();
2472
    }
2473
2474
    /**
2475
     * Clears the UnitOfWork.
2476
     *
2477
     * @param string|null $entityName if given, only entities of this type will get detached.
2478
     *
2479
     * @return void
2480
     *
2481
     * @throws ORMInvalidArgumentException if an invalid entity name is given
2482
     */
2483 451
    public function clear($entityName = null)
2484
    {
2485 451
        if ($entityName === null) {
2486 449
            $this->identityMap =
2487 449
            $this->entityIdentifiers =
2488 449
            $this->originalEntityData =
2489 449
            $this->entityChangeSets =
2490 449
            $this->entityStates =
2491 449
            $this->scheduledForSynchronization =
2492 449
            $this->entityInsertions =
2493 449
            $this->entityUpdates =
2494 449
            $this->entityDeletions =
2495 449
            $this->nonCascadedNewDetectedEntities =
2496 449
            $this->collectionDeletions =
2497 449
            $this->collectionUpdates =
2498 449
            $this->extraUpdates =
2499 449
            $this->readOnlyObjects =
2500 449
            $this->visitedCollections =
2501 449
            $this->orphanRemovals = [];
2502
        } else {
2503 3
            $this->clearIdentityMapForEntityName($entityName);
2504 3
            $this->clearEntityInsertionsForEntityName($entityName);
2505
        }
2506
2507 451
        if ($this->evm->hasListeners(Events::onClear)) {
2508 5
            $this->evm->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->em, $entityName));
2509
        }
2510 451
    }
2511
2512
    /**
2513
     * INTERNAL:
2514
     * Schedules an orphaned entity for removal. The remove() operation will be
2515
     * invoked on that entity at the beginning of the next commit of this
2516
     * UnitOfWork.
2517
     *
2518
     * @ignore
2519
     *
2520
     * @param object $entity
2521
     *
2522
     * @return void
2523
     */
2524 6
    public function scheduleOrphanRemoval($entity)
2525
    {
2526 6
        $this->orphanRemovals[spl_object_hash($entity)] = $entity;
2527 6
    }
2528
2529
    /**
2530
     * INTERNAL:
2531
     * Cancels a previously scheduled orphan removal.
2532
     *
2533
     * @ignore
2534
     *
2535
     * @param object $entity
2536
     *
2537
     * @return void
2538
     */
2539 19
    public function cancelOrphanRemoval($entity)
2540
    {
2541 19
        unset($this->orphanRemovals[spl_object_hash($entity)]);
2542 19
    }
2543
2544
    /**
2545
     * INTERNAL:
2546
     * Schedules a complete collection for removal when this UnitOfWork commits.
2547
     *
2548
     * @param PersistentCollection $coll
2549
     *
2550
     * @return void
2551
     */
2552 3
    public function scheduleCollectionDeletion(PersistentCollection $coll)
2553
    {
2554 3
        $coid = spl_object_hash($coll);
2555
2556
        // TODO: if $coll is already scheduled for recreation ... what to do?
2557
        // Just remove $coll from the scheduled recreations?
2558 3
        unset($this->collectionUpdates[$coid]);
2559
2560 3
        $this->collectionDeletions[$coid] = $coll;
2561 3
    }
2562
2563
    /**
2564
     * @param PersistentCollection $coll
2565
     *
2566
     * @return bool
2567
     */
2568
    public function isCollectionScheduledForDeletion(PersistentCollection $coll)
2569
    {
2570
        return isset($this->collectionDeletions[spl_object_hash($coll)]);
2571
    }
2572
2573
    /**
2574
     * @param ClassMetadata $class
2575
     *
2576
     * @return \Doctrine\Common\Persistence\ObjectManagerAware|object
2577
     */
2578 179
    private function newInstance($class)
2579
    {
2580 179
        $entity = $class->newInstance();
2581
2582 179
        if ($entity instanceof \Doctrine\Common\Persistence\ObjectManagerAware) {
2583 3
            $entity->injectObjectManager($this->em, $class);
2584
        }
2585
2586 179
        return $entity;
2587
    }
2588
2589
    /**
2590
     * INTERNAL:
2591
     * Creates an entity. Used for reconstitution of persistent entities.
2592
     *
2593
     * Internal note: Highly performance-sensitive method.
2594
     *
2595
     * @ignore
2596
     *
2597
     * @param string $className The name of the entity class.
2598
     * @param array  $data      The data for the entity.
2599
     * @param array  $hints     Any hints to account for during reconstitution/lookup of the entity.
2600
     *
2601
     * @return object The managed entity instance.
2602
     *
2603
     * @todo Rename: getOrCreateEntity
2604
     */
2605 194
    public function createEntity($className, array $data, &$hints = [])
2606
    {
2607 194
        $class = $this->em->getClassMetadata($className);
2608
2609 194
        $id = $this->identifierFlattener->flattenIdentifier($class, $data);
2610 194
        $idHash = implode(' ', $id);
2611
2612 194
        if (isset($this->identityMap[$class->rootEntityName][$idHash])) {
0 ignored issues
show
Bug introduced by
Accessing rootEntityName on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2613 45
            $entity = $this->identityMap[$class->rootEntityName][$idHash];
2614 45
            $oid = spl_object_hash($entity);
2615
2616
            if (
2617 45
                isset($hints[Query::HINT_REFRESH])
2618 45
                && isset($hints[Query::HINT_REFRESH_ENTITY])
2619 45
                && ($unmanagedProxy = $hints[Query::HINT_REFRESH_ENTITY]) !== $entity
2620 45
                && $unmanagedProxy instanceof Proxy
2621 45
                && $this->isIdentifierEquals($unmanagedProxy, $entity)
2622
            ) {
2623
                // DDC-1238 - we have a managed instance, but it isn't the provided one.
2624
                // Therefore we clear its identifier. Also, we must re-fetch metadata since the
2625
                // refreshed object may be anything
2626
2627 1
                foreach ($class->identifier as $fieldName) {
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...
2628 1
                    $class->reflFields[$fieldName]->setValue($unmanagedProxy, null);
0 ignored issues
show
Bug introduced by
Accessing reflFields on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2629
                }
2630
2631 1
                return $unmanagedProxy;
2632
            }
2633
2634 44
            if ($entity instanceof Proxy && ! $entity->__isInitialized()) {
2635 1
                $entity->__setInitialized(true);
2636
2637 1
                if ($entity instanceof NotifyPropertyChanged) {
2638 1
                    $entity->addPropertyChangedListener($this);
2639
                }
2640
            } else {
2641 43
                if ( ! isset($hints[Query::HINT_REFRESH])
2642 43
                    || (isset($hints[Query::HINT_REFRESH_ENTITY]) && $hints[Query::HINT_REFRESH_ENTITY] !== $entity)) {
2643 34
                    return $entity;
2644
                }
2645
            }
2646
2647
            // inject ObjectManager upon refresh.
2648 11
            if ($entity instanceof ObjectManagerAware) {
2649 1
                $entity->injectObjectManager($this->em, $class);
2650
            }
2651
2652 11
            $this->originalEntityData[$oid] = $data;
2653
        } else {
2654 173
            $entity = $this->newInstance($class);
2655 173
            $oid    = spl_object_hash($entity);
2656
2657 173
            $this->entityIdentifiers[$oid]  = $id;
2658 173
            $this->entityStates[$oid]       = self::STATE_MANAGED;
2659 173
            $this->originalEntityData[$oid] = $data;
2660
2661 173
            $this->identityMap[$class->rootEntityName][$idHash] = $entity;
2662
2663 173
            if ($entity instanceof NotifyPropertyChanged) {
2664 1
                $entity->addPropertyChangedListener($this);
2665
            }
2666
        }
2667
2668 183
        foreach ($data as $field => $value) {
2669 183
            if (isset($class->fieldMappings[$field])) {
0 ignored issues
show
Bug introduced by
Accessing fieldMappings on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2670 183
                $class->reflFields[$field]->setValue($entity, $value);
2671
            }
2672
        }
2673
2674
        // Loading the entity right here, if its in the eager loading map get rid of it there.
2675 183
        unset($this->eagerLoadingEntities[$class->rootEntityName][$idHash]);
2676
2677 183
        if (isset($this->eagerLoadingEntities[$class->rootEntityName]) && ! $this->eagerLoadingEntities[$class->rootEntityName]) {
2678
            unset($this->eagerLoadingEntities[$class->rootEntityName]);
2679
        }
2680
2681
        // Properly initialize any unfetched associations, if partial objects are not allowed.
2682 183
        if (isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
2683 33
            return $entity;
2684
        }
2685
2686 150
        foreach ($class->associationMappings as $field => $assoc) {
2687
            // Check if the association is not among the fetch-joined associations already.
2688 46
            if (isset($hints['fetchAlias']) && isset($hints['fetched'][$hints['fetchAlias']][$field])) {
2689 5
                continue;
2690
            }
2691
2692 43
            $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
2693
2694
            switch (true) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $assoc['type'] & Doctrin...g\ClassMetadata::TO_ONE of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
2695 43
                case ($assoc['type'] & ClassMetadata::TO_ONE):
2696 6
                    if ( ! $assoc['isOwningSide']) {
2697
2698
                        // use the given entity association
2699 2
                        if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) {
2700
2701
                            $this->originalEntityData[$oid][$field] = $data[$field];
2702
2703
                            $class->reflFields[$field]->setValue($entity, $data[$field]);
2704
                            $targetClass->reflFields[$assoc['mappedBy']]->setValue($data[$field], $entity);
2705
2706
                            continue 2;
2707
                        }
2708
2709
                        // Inverse side of x-to-one can never be lazy
2710 2
                        $class->reflFields[$field]->setValue($entity, $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity));
2711
2712 2
                        continue 2;
2713
                    }
2714
2715
                    // use the entity association
2716 6
                    if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) {
2717
                        $class->reflFields[$field]->setValue($entity, $data[$field]);
2718
                        $this->originalEntityData[$oid][$field] = $data[$field];
2719
2720
                        break;
2721
                    }
2722
2723 6
                    $associatedId = [];
2724
2725
                    // TODO: Is this even computed right in all cases of composite keys?
2726 6
                    foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
2727 6
                        $joinColumnValue = $data[$srcColumn] ?? null;
2728
2729 6
                        if ($joinColumnValue !== null) {
2730 2
                            if ($targetClass->containsForeignIdentifier) {
0 ignored issues
show
Bug introduced by
Accessing containsForeignIdentifier on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2731
                                $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue;
2732
                            } else {
2733 2
                                $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;
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...
2734
                            }
2735 4
                        } elseif ($targetClass->containsForeignIdentifier
2736 4
                            && in_array($targetClass->getFieldForColumn($targetColumn), $targetClass->identifier, true)
2737
                        ) {
2738
                            // the missing key is part of target's entity primary key
2739
                            $associatedId = [];
2740 6
                            break;
2741
                        }
2742
                    }
2743
2744 6
                    if ( ! $associatedId) {
2745
                        // Foreign key is NULL
2746 4
                        $class->reflFields[$field]->setValue($entity, null);
2747 4
                        $this->originalEntityData[$oid][$field] = null;
2748
2749 4
                        break;
2750
                    }
2751
2752 2
                    if ( ! isset($hints['fetchMode'][$class->name][$field])) {
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2753 2
                        $hints['fetchMode'][$class->name][$field] = $assoc['fetch'];
2754
                    }
2755
2756
                    // Foreign key is set
2757
                    // Check identity map first
2758
                    // FIXME: Can break easily with composite keys if join column values are in
2759
                    //        wrong order. The correct order is the one in ClassMetadata#identifier.
2760 2
                    $relatedIdHash = implode(' ', $associatedId);
2761
2762
                    switch (true) {
2763 2
                        case (isset($this->identityMap[$targetClass->rootEntityName][$relatedIdHash])):
2764
                            $newValue = $this->identityMap[$targetClass->rootEntityName][$relatedIdHash];
2765
2766
                            // If this is an uninitialized proxy, we are deferring eager loads,
2767
                            // this association is marked as eager fetch, and its an uninitialized proxy (wtf!)
2768
                            // then we can append this entity for eager loading!
2769
                            if ($hints['fetchMode'][$class->name][$field] == ClassMetadata::FETCH_EAGER &&
2770
                                isset($hints[self::HINT_DEFEREAGERLOAD]) &&
2771
                                !$targetClass->isIdentifierComposite &&
0 ignored issues
show
Bug introduced by
Accessing isIdentifierComposite on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2772
                                $newValue instanceof Proxy &&
2773
                                $newValue->__isInitialized__ === false) {
0 ignored issues
show
Bug introduced by
Accessing __isInitialized__ on the interface Doctrine\ORM\Proxy\Proxy suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2774
2775
                                $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
2776
                            }
2777
2778
                            break;
2779
2780 2
                        case ($targetClass->subClasses):
0 ignored issues
show
Bug introduced by
Accessing subClasses on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2781
                            // If it might be a subtype, it can not be lazy. There isn't even
2782
                            // a way to solve this with deferred eager loading, which means putting
2783
                            // an entity with subclasses at a *-to-one location is really bad! (performance-wise)
2784
                            $newValue = $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity, $associatedId);
2785
                            break;
2786
2787
                        default:
2788
                            switch (true) {
2789
                                // We are negating the condition here. Other cases will assume it is valid!
2790 2
                                case ($hints['fetchMode'][$class->name][$field] !== ClassMetadata::FETCH_EAGER):
2791 2
                                    $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
2792 2
                                    break;
2793
2794
                                // Deferred eager load only works for single identifier classes
2795
                                case (isset($hints[self::HINT_DEFEREAGERLOAD]) && ! $targetClass->isIdentifierComposite):
2796
                                    // TODO: Is there a faster approach?
2797
                                    $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
2798
2799
                                    $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
2800
                                    break;
2801
2802
                                default:
2803
                                    // TODO: This is very imperformant, ignore it?
2804
                                    $newValue = $this->em->find($assoc['targetEntity'], $associatedId);
2805
                                    break;
2806
                            }
2807
2808
                            // PERF: Inlined & optimized code from UnitOfWork#registerManaged()
2809 2
                            $newValueOid = spl_object_hash($newValue);
2810 2
                            $this->entityIdentifiers[$newValueOid] = $associatedId;
2811 2
                            $this->identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue;
2812
2813
                            if (
2814 2
                                $newValue instanceof NotifyPropertyChanged &&
2815 2
                                ( ! $newValue instanceof Proxy || $newValue->__isInitialized())
2816
                            ) {
2817
                                $newValue->addPropertyChangedListener($this);
2818
                            }
2819 2
                            $this->entityStates[$newValueOid] = self::STATE_MANAGED;
2820
                            // make sure that when an proxy is then finally loaded, $this->originalEntityData is set also!
2821 2
                            break;
2822
                    }
2823
2824 2
                    $this->originalEntityData[$oid][$field] = $newValue;
2825 2
                    $class->reflFields[$field]->setValue($entity, $newValue);
2826
2827 2
                    if ($assoc['inversedBy'] && $assoc['type'] & ClassMetadata::ONE_TO_ONE) {
2828
                        $inverseAssoc = $targetClass->associationMappings[$assoc['inversedBy']];
0 ignored issues
show
Bug introduced by
Accessing associationMappings on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2829
                        $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($newValue, $entity);
2830
                    }
2831
2832 2
                    break;
2833
2834
                default:
2835
                    // Ignore if its a cached collection
2836 42
                    if (isset($hints[Query::HINT_CACHE_ENABLED]) && $class->getFieldValue($entity, $field) instanceof PersistentCollection) {
2837
                        break;
2838
                    }
2839
2840
                    // use the given collection
2841 42
                    if (isset($data[$field]) && $data[$field] instanceof PersistentCollection) {
2842
2843
                        $data[$field]->setOwner($entity, $assoc);
2844
2845
                        $class->reflFields[$field]->setValue($entity, $data[$field]);
2846
                        $this->originalEntityData[$oid][$field] = $data[$field];
2847
2848
                        break;
2849
                    }
2850
2851
                    // Inject collection
2852 42
                    $pColl = new PersistentCollection($this->em, $targetClass, new ArrayCollection);
2853 42
                    $pColl->setOwner($entity, $assoc);
2854 42
                    $pColl->setInitialized(false);
2855
2856 42
                    $reflField = $class->reflFields[$field];
2857 42
                    $reflField->setValue($entity, $pColl);
2858
2859 42
                    if ($assoc['fetch'] == ClassMetadata::FETCH_EAGER) {
2860 1
                        $this->loadCollection($pColl);
2861 1
                        $pColl->takeSnapshot();
2862
                    }
2863
2864 42
                    $this->originalEntityData[$oid][$field] = $pColl;
2865 43
                    break;
2866
            }
2867
        }
2868
2869
        // defer invoking of postLoad event to hydration complete step
2870 150
        $this->hydrationCompleteHandler->deferPostLoadInvoking($class, $entity);
2871
2872 150
        return $entity;
2873
    }
2874
2875
    /**
2876
     * @return void
2877
     */
2878 241
    public function triggerEagerLoads()
2879
    {
2880 241
        if ( ! $this->eagerLoadingEntities) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->eagerLoadingEntities 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...
2881 241
            return;
2882
        }
2883
2884
        // avoid infinite recursion
2885
        $eagerLoadingEntities       = $this->eagerLoadingEntities;
2886
        $this->eagerLoadingEntities = [];
2887
2888
        foreach ($eagerLoadingEntities as $entityName => $ids) {
2889
            if ( ! $ids) {
2890
                continue;
2891
            }
2892
2893
            $class = $this->em->getClassMetadata($entityName);
2894
2895
            $this->getEntityPersister($entityName)->loadAll(
2896
                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...
Bug introduced by
It seems like array_combine($class->id...ay(array_values($ids))) can also be of type false; however, parameter $criteria of Doctrine\ORM\Persisters\...ityPersister::loadAll() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

2896
                /** @scrutinizer ignore-type */ array_combine($class->identifier, [array_values($ids)])
Loading history...
2897
            );
2898
        }
2899
    }
2900
2901
    /**
2902
     * Initializes (loads) an uninitialized persistent collection of an entity.
2903
     *
2904
     * @param \Doctrine\ORM\PersistentCollection $collection The collection to initialize.
2905
     *
2906
     * @return void
2907
     *
2908
     * @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733.
2909
     */
2910 24
    public function loadCollection(PersistentCollection $collection)
2911
    {
2912 24
        $assoc     = $collection->getMapping();
2913 24
        $persister = $this->getEntityPersister($assoc['targetEntity']);
2914
2915 24
        switch ($assoc['type']) {
2916 24
            case ClassMetadata::ONE_TO_MANY:
2917
                $persister->loadOneToManyCollection($assoc, $collection->getOwner(), $collection);
2918
                break;
2919
2920 24
            case ClassMetadata::MANY_TO_MANY:
2921 24
                $persister->loadManyToManyCollection($assoc, $collection->getOwner(), $collection);
2922 24
                break;
2923
        }
2924
2925 24
        $collection->setInitialized(true);
2926 24
    }
2927
2928
    /**
2929
     * Gets the identity map of the UnitOfWork.
2930
     *
2931
     * @return array
2932
     */
2933
    public function getIdentityMap()
2934
    {
2935
        return $this->identityMap;
2936
    }
2937
2938
    /**
2939
     * Gets the original data of an entity. The original data is the data that was
2940
     * present at the time the entity was reconstituted from the database.
2941
     *
2942
     * @param object $entity
2943
     *
2944
     * @return array
2945
     */
2946 58
    public function getOriginalEntityData($entity)
2947
    {
2948 58
        $oid = spl_object_hash($entity);
2949
2950 58
        return isset($this->originalEntityData[$oid])
2951 54
            ? $this->originalEntityData[$oid]
2952 58
            : [];
2953
    }
2954
2955
    /**
2956
     * @ignore
2957
     *
2958
     * @param object $entity
2959
     * @param array  $data
2960
     *
2961
     * @return void
2962
     */
2963
    public function setOriginalEntityData($entity, array $data)
2964
    {
2965
        $this->originalEntityData[spl_object_hash($entity)] = $data;
2966
    }
2967
2968
    /**
2969
     * INTERNAL:
2970
     * Sets a property value of the original data array of an entity.
2971
     *
2972
     * @ignore
2973
     *
2974
     * @param string $oid
2975
     * @param string $property
2976
     * @param mixed  $value
2977
     *
2978
     * @return void
2979
     */
2980 22
    public function setOriginalEntityProperty($oid, $property, $value)
2981
    {
2982 22
        $this->originalEntityData[$oid][$property] = $value;
2983 22
    }
2984
2985
    /**
2986
     * Gets the identifier of an entity.
2987
     * The returned value is always an array of identifier values. If the entity
2988
     * has a composite identifier then the identifier values are in the same
2989
     * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
2990
     *
2991
     * @param object $entity
2992
     *
2993
     * @return array The identifier values.
2994
     */
2995 161
    public function getEntityIdentifier($entity)
2996
    {
2997 161
        return $this->entityIdentifiers[spl_object_hash($entity)];
2998
    }
2999
3000
    /**
3001
     * Processes an entity instance to extract their identifier values.
3002
     *
3003
     * @param object $entity The entity instance.
3004
     *
3005
     * @return mixed A scalar value.
3006
     *
3007
     * @throws \Doctrine\ORM\ORMInvalidArgumentException
3008
     */
3009 9
    public function getSingleIdentifierValue($entity)
3010
    {
3011 9
        $class = $this->em->getClassMetadata(get_class($entity));
3012
3013 8
        if ($class->isIdentifierComposite) {
0 ignored issues
show
Bug introduced by
Accessing isIdentifierComposite on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
3014
            throw ORMInvalidArgumentException::invalidCompositeIdentifier();
3015
        }
3016
3017 8
        $values = $this->isInIdentityMap($entity)
3018 2
            ? $this->getEntityIdentifier($entity)
3019 8
            : $class->getIdentifierValues($entity);
3020
3021 8
        return isset($values[$class->identifier[0]]) ? $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...
3022
    }
3023
3024
    /**
3025
     * Tries to find an entity with the given identifier in the identity map of
3026
     * this UnitOfWork.
3027
     *
3028
     * @param mixed  $id            The entity identifier to look for.
3029
     * @param string $rootClassName The name of the root class of the mapped entity hierarchy.
3030
     *
3031
     * @return object|bool Returns the entity with the specified identifier if it exists in
3032
     *                     this UnitOfWork, FALSE otherwise.
3033
     */
3034 116
    public function tryGetById($id, $rootClassName)
3035
    {
3036 116
        $idHash = implode(' ', (array) $id);
3037
3038 116
        return isset($this->identityMap[$rootClassName][$idHash])
3039 17
            ? $this->identityMap[$rootClassName][$idHash]
3040 116
            : false;
3041
    }
3042
3043
    /**
3044
     * Schedules an entity for dirty-checking at commit-time.
3045
     *
3046
     * @param object $entity The entity to schedule for dirty-checking.
3047
     *
3048
     * @return void
3049
     *
3050
     * @todo Rename: scheduleForSynchronization
3051
     */
3052 6
    public function scheduleForDirtyCheck($entity)
3053
    {
3054 6
        $rootClassName = $this->em->getClassMetadata(get_class($entity))->rootEntityName;
0 ignored issues
show
Bug introduced by
Accessing rootEntityName on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
3055
3056 6
        $this->scheduledForSynchronization[$rootClassName][spl_object_hash($entity)] = $entity;
3057 6
    }
3058
3059
    /**
3060
     * Checks whether the UnitOfWork has any pending insertions.
3061
     *
3062
     * @return boolean TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
3063
     */
3064
    public function hasPendingInsertions()
3065
    {
3066
        return ! empty($this->entityInsertions);
3067
    }
3068
3069
    /**
3070
     * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
3071
     * number of entities in the identity map.
3072
     *
3073
     * @return integer
3074
     */
3075
    public function size()
3076
    {
3077
        $countArray = array_map('count', $this->identityMap);
3078
3079
        return array_sum($countArray);
3080
    }
3081
3082
    /**
3083
     * Gets the EntityPersister for an Entity.
3084
     *
3085
     * @param string $entityName The name of the Entity.
3086
     *
3087
     * @return \Doctrine\ORM\Persisters\Entity\EntityPersister
3088
     */
3089 284
    public function getEntityPersister($entityName)
3090
    {
3091 284
        if (isset($this->persisters[$entityName])) {
3092 173
            return $this->persisters[$entityName];
3093
        }
3094
3095 284
        $class = $this->em->getClassMetadata($entityName);
3096
3097
        switch (true) {
3098 284
            case ($class->isInheritanceTypeNone()):
3099 239
                $persister = new BasicEntityPersister($this->em, $class);
3100 239
                break;
3101
3102 75
            case ($class->isInheritanceTypeSingleTable()):
3103 33
                $persister = new SingleTablePersister($this->em, $class);
3104 33
                break;
3105
3106 68
            case ($class->isInheritanceTypeJoined()):
3107 68
                $persister = new JoinedSubclassPersister($this->em, $class);
3108 68
                break;
3109
3110
            default:
3111
                throw new \RuntimeException('No persister found for entity.');
3112
        }
3113
3114 284
        if ($this->hasCache && $class->cache !== null) {
0 ignored issues
show
Bug introduced by
Accessing cache on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
3115 70
            $persister = $this->em->getConfiguration()
3116 70
                ->getSecondLevelCacheConfiguration()
3117 70
                ->getCacheFactory()
3118 70
                ->buildCachedEntityPersister($this->em, $persister, $class);
3119
        }
3120
3121 284
        $this->persisters[$entityName] = $persister;
3122
3123 284
        return $this->persisters[$entityName];
3124
    }
3125
3126
    /**
3127
     * Gets a collection persister for a collection-valued association.
3128
     *
3129
     * @param array $association
3130
     *
3131
     * @return \Doctrine\ORM\Persisters\Collection\CollectionPersister
3132
     */
3133 80
    public function getCollectionPersister(array $association)
3134
    {
3135 80
        $role = isset($association['cache'])
3136 30
            ? $association['sourceEntity'] . '::' . $association['fieldName']
3137 80
            : $association['type'];
3138
3139 80
        if (isset($this->collectionPersisters[$role])) {
3140 63
            return $this->collectionPersisters[$role];
3141
        }
3142
3143 80
        $persister = ClassMetadata::ONE_TO_MANY === $association['type']
3144 31
            ? new OneToManyPersister($this->em)
3145 80
            : new ManyToManyPersister($this->em);
3146
3147 80
        if ($this->hasCache && isset($association['cache'])) {
3148 30
            $persister = $this->em->getConfiguration()
3149 30
                ->getSecondLevelCacheConfiguration()
3150 30
                ->getCacheFactory()
3151 30
                ->buildCachedCollectionPersister($this->em, $persister, $association);
3152
        }
3153
3154 80
        $this->collectionPersisters[$role] = $persister;
3155
3156 80
        return $this->collectionPersisters[$role];
3157
    }
3158
3159
    /**
3160
     * INTERNAL:
3161
     * Registers an entity as managed.
3162
     *
3163
     * @param object $entity The entity.
3164
     * @param array  $id     The identifier values.
3165
     * @param array  $data   The original entity data.
3166
     *
3167
     * @return void
3168
     */
3169 97
    public function registerManaged($entity, array $id, array $data)
3170
    {
3171 97
        $oid = spl_object_hash($entity);
3172
3173 97
        $this->entityIdentifiers[$oid]  = $id;
3174 97
        $this->entityStates[$oid]       = self::STATE_MANAGED;
3175 97
        $this->originalEntityData[$oid] = $data;
3176
3177 97
        $this->addToIdentityMap($entity);
3178
3179 91
        if ($entity instanceof NotifyPropertyChanged && ( ! $entity instanceof Proxy || $entity->__isInitialized())) {
3180 1
            $entity->addPropertyChangedListener($this);
3181
        }
3182 91
    }
3183
3184
    /**
3185
     * INTERNAL:
3186
     * Clears the property changeset of the entity with the given OID.
3187
     *
3188
     * @param string $oid The entity's OID.
3189
     *
3190
     * @return void
3191
     */
3192 8
    public function clearEntityChangeSet($oid)
3193
    {
3194 8
        unset($this->entityChangeSets[$oid]);
3195 8
    }
3196
3197
    /* PropertyChangedListener implementation */
3198
3199
    /**
3200
     * Notifies this UnitOfWork of a property change in an entity.
3201
     *
3202
     * @param object $entity       The entity that owns the property.
3203
     * @param string $propertyName The name of the property that changed.
3204
     * @param mixed  $oldValue     The old value of the property.
3205
     * @param mixed  $newValue     The new value of the property.
3206
     *
3207
     * @return void
3208
     */
3209 3
    public function propertyChanged($entity, $propertyName, $oldValue, $newValue)
3210
    {
3211 3
        $oid   = spl_object_hash($entity);
3212 3
        $class = $this->em->getClassMetadata(get_class($entity));
3213
3214 3
        $isAssocField = isset($class->associationMappings[$propertyName]);
0 ignored issues
show
Bug introduced by
Accessing associationMappings on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
3215
3216 3
        if ( ! $isAssocField && ! isset($class->fieldMappings[$propertyName])) {
0 ignored issues
show
Bug introduced by
Accessing fieldMappings on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
3217 1
            return; // ignore non-persistent fields
3218
        }
3219
3220
        // Update changeset and mark entity for synchronization
3221 3
        $this->entityChangeSets[$oid][$propertyName] = [$oldValue, $newValue];
3222
3223 3
        if ( ! isset($this->scheduledForSynchronization[$class->rootEntityName][$oid])) {
0 ignored issues
show
Bug introduced by
Accessing rootEntityName on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
3224 3
            $this->scheduleForDirtyCheck($entity);
3225
        }
3226 3
    }
3227
3228
    /**
3229
     * Gets the currently scheduled entity insertions in this UnitOfWork.
3230
     *
3231
     * @return array
3232
     */
3233 1
    public function getScheduledEntityInsertions()
3234
    {
3235 1
        return $this->entityInsertions;
3236
    }
3237
3238
    /**
3239
     * Gets the currently scheduled entity updates in this UnitOfWork.
3240
     *
3241
     * @return array
3242
     */
3243 1
    public function getScheduledEntityUpdates()
3244
    {
3245 1
        return $this->entityUpdates;
3246
    }
3247
3248
    /**
3249
     * Gets the currently scheduled entity deletions in this UnitOfWork.
3250
     *
3251
     * @return array
3252
     */
3253
    public function getScheduledEntityDeletions()
3254
    {
3255
        return $this->entityDeletions;
3256
    }
3257
3258
    /**
3259
     * Gets the currently scheduled complete collection deletions
3260
     *
3261
     * @return array
3262
     */
3263 1
    public function getScheduledCollectionDeletions()
3264
    {
3265 1
        return $this->collectionDeletions;
3266
    }
3267
3268
    /**
3269
     * Gets the currently scheduled collection inserts, updates and deletes.
3270
     *
3271
     * @return array
3272
     */
3273
    public function getScheduledCollectionUpdates()
3274
    {
3275
        return $this->collectionUpdates;
3276
    }
3277
3278
    /**
3279
     * Helper method to initialize a lazy loading proxy or persistent collection.
3280
     *
3281
     * @param object $obj
3282
     *
3283
     * @return void
3284
     */
3285
    public function initializeObject($obj)
3286
    {
3287
        if ($obj instanceof Proxy) {
3288
            $obj->__load();
3289
3290
            return;
3291
        }
3292
3293
        if ($obj instanceof PersistentCollection) {
3294
            $obj->initialize();
3295
        }
3296
    }
3297
3298
    /**
3299
     * Helper method to show an object as string.
3300
     *
3301
     * @param object $obj
3302
     *
3303
     * @return string
3304
     */
3305 1
    private static function objToStr($obj)
3306
    {
3307 1
        return method_exists($obj, '__toString') ? (string) $obj : get_class($obj).'@'.spl_object_hash($obj);
3308
    }
3309
3310
    /**
3311
     * Marks an entity as read-only so that it will not be considered for updates during UnitOfWork#commit().
3312
     *
3313
     * This operation cannot be undone as some parts of the UnitOfWork now keep gathering information
3314
     * on this object that might be necessary to perform a correct update.
3315
     *
3316
     * @param object $object
3317
     *
3318
     * @return void
3319
     *
3320
     * @throws ORMInvalidArgumentException
3321
     */
3322 5
    public function markReadOnly($object)
3323
    {
3324 5
        if ( ! is_object($object) || ! $this->isInIdentityMap($object)) {
3325 1
            throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
3326
        }
3327
3328 4
        $this->readOnlyObjects[spl_object_hash($object)] = true;
3329 4
    }
3330
3331
    /**
3332
     * Is this entity read only?
3333
     *
3334
     * @param object $object
3335
     *
3336
     * @return bool
3337
     *
3338
     * @throws ORMInvalidArgumentException
3339
     */
3340 3
    public function isReadOnly($object)
3341
    {
3342 3
        if ( ! is_object($object)) {
3343
            throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
3344
        }
3345
3346 3
        return isset($this->readOnlyObjects[spl_object_hash($object)]);
3347
    }
3348
3349
    /**
3350
     * Perform whatever processing is encapsulated here after completion of the transaction.
3351
     */
3352 204
    private function afterTransactionComplete()
3353
    {
3354
        $this->performCallbackOnCachedPersister(function (CachedPersister $persister) {
3355 34
            $persister->afterTransactionComplete();
3356 204
        });
3357 204
    }
3358
3359
    /**
3360
     * Perform whatever processing is encapsulated here after completion of the rolled-back.
3361
     */
3362 22
    private function afterTransactionRolledBack()
3363
    {
3364
        $this->performCallbackOnCachedPersister(function (CachedPersister $persister) {
3365 6
            $persister->afterTransactionRolledBack();
3366 22
        });
3367 22
    }
3368
3369
    /**
3370
     * Performs an action after the transaction.
3371
     *
3372
     * @param callable $callback
3373
     */
3374 223
    private function performCallbackOnCachedPersister(callable $callback)
3375
    {
3376 223
        if ( ! $this->hasCache) {
3377 185
            return;
3378
        }
3379
3380 38
        foreach (array_merge($this->persisters, $this->collectionPersisters) as $persister) {
3381 38
            if ($persister instanceof CachedPersister) {
3382 38
                $callback($persister);
3383
            }
3384
        }
3385 38
    }
3386
3387 227
    private function dispatchOnFlushEvent()
3388
    {
3389 227
        if ($this->evm->hasListeners(Events::onFlush)) {
3390 2
            $this->evm->dispatchEvent(Events::onFlush, new OnFlushEventArgs($this->em));
3391
        }
3392 227
    }
3393
3394 208
    private function dispatchPostFlushEvent()
3395
    {
3396 208
        if ($this->evm->hasListeners(Events::postFlush)) {
3397 2
            $this->evm->dispatchEvent(Events::postFlush, new PostFlushEventArgs($this->em));
3398
        }
3399 207
    }
3400
3401
    /**
3402
     * Verifies if two given entities actually are the same based on identifier comparison
3403
     *
3404
     * @param object $entity1
3405
     * @param object $entity2
3406
     *
3407
     * @return bool
3408
     */
3409 1
    private function isIdentifierEquals($entity1, $entity2)
3410
    {
3411 1
        if ($entity1 === $entity2) {
3412
            return true;
3413
        }
3414
3415 1
        $class = $this->em->getClassMetadata(get_class($entity1));
3416
3417 1
        if ($class !== $this->em->getClassMetadata(get_class($entity2))) {
3418
            return false;
3419
        }
3420
3421 1
        $oid1 = spl_object_hash($entity1);
3422 1
        $oid2 = spl_object_hash($entity2);
3423
3424 1
        $id1 = isset($this->entityIdentifiers[$oid1])
3425 1
            ? $this->entityIdentifiers[$oid1]
3426 1
            : $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($entity1));
3427 1
        $id2 = isset($this->entityIdentifiers[$oid2])
3428 1
            ? $this->entityIdentifiers[$oid2]
3429 1
            : $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($entity2));
3430
3431 1
        return $id1 === $id2 || implode(' ', $id1) === implode(' ', $id2);
3432
    }
3433
3434
    /**
3435
     * @throws ORMInvalidArgumentException
3436
     */
3437 225
    private function assertThatThereAreNoUnintentionallyNonPersistedAssociations() : void
3438
    {
3439 225
        $entitiesNeedingCascadePersist = \array_diff_key($this->nonCascadedNewDetectedEntities, $this->entityInsertions);
3440
3441 225
        $this->nonCascadedNewDetectedEntities = [];
3442
3443 225
        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...
3444 3
            throw ORMInvalidArgumentException::newEntitiesFoundThroughRelationships(
3445 3
                \array_values($entitiesNeedingCascadePersist)
3446
            );
3447
        }
3448 223
    }
3449
3450
    /**
3451
     * @param object $entity
3452
     * @param object $managedCopy
3453
     *
3454
     * @throws ORMException
3455
     * @throws OptimisticLockException
3456
     * @throws TransactionRequiredException
3457
     */
3458 20
    private function mergeEntityStateIntoManagedCopy($entity, $managedCopy)
3459
    {
3460 20
        if (! $this->isLoaded($entity)) {
3461 6
            return;
3462
        }
3463
3464 14
        if (! $this->isLoaded($managedCopy)) {
3465 1
            $managedCopy->__load();
3466
        }
3467
3468 14
        $class = $this->em->getClassMetadata(get_class($entity));
3469
3470 14
        foreach ($this->reflectionPropertiesGetter->getProperties($class->name) as $prop) {
3471 14
            $name = $prop->name;
3472
3473 14
            $prop->setAccessible(true);
3474
3475 14
            if ( ! isset($class->associationMappings[$name])) {
0 ignored issues
show
Bug introduced by
Accessing associationMappings on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
3476 14
                if ( ! $class->isIdentifier($name)) {
3477 14
                    $prop->setValue($managedCopy, $prop->getValue($entity));
3478
                }
3479
            } else {
3480 10
                $assoc2 = $class->associationMappings[$name];
3481
3482 10
                if ($assoc2['type'] & ClassMetadata::TO_ONE) {
3483 6
                    $other = $prop->getValue($entity);
3484 6
                    if ($other === null) {
3485 3
                        $prop->setValue($managedCopy, null);
3486
                    } else {
3487 3
                        if ($other instanceof Proxy && !$other->__isInitialized()) {
3488
                            // do not merge fields marked lazy that have not been fetched.
3489
                            continue;
3490
                        }
3491
3492 3
                        if ( ! $assoc2['isCascadeMerge']) {
3493 1
                            if ($this->getEntityState($other) === self::STATE_DETACHED) {
3494
                                $targetClass = $this->em->getClassMetadata($assoc2['targetEntity']);
3495
                                $relatedId   = $targetClass->getIdentifierValues($other);
3496
3497
                                if ($targetClass->subClasses) {
0 ignored issues
show
Bug introduced by
Accessing subClasses on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
3498
                                    $other = $this->em->find($targetClass->name, $relatedId);
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
3499
                                } else {
3500
                                    $other = $this->em->getProxyFactory()->getProxy(
3501
                                        $assoc2['targetEntity'],
3502
                                        $relatedId
3503
                                    );
3504
                                    $this->registerManaged($other, $relatedId, []);
3505
                                }
3506
                            }
3507
3508 6
                            $prop->setValue($managedCopy, $other);
3509
                        }
3510
                    }
3511
                } else {
3512 7
                    $mergeCol = $prop->getValue($entity);
3513
3514 7
                    if ($mergeCol instanceof PersistentCollection && ! $mergeCol->isInitialized()) {
3515
                        // do not merge fields marked lazy that have not been fetched.
3516
                        // keep the lazy persistent collection of the managed copy.
3517
                        continue;
3518
                    }
3519
3520 7
                    $managedCol = $prop->getValue($managedCopy);
3521
3522 7
                    if ( ! $managedCol) {
3523 3
                        $managedCol = new PersistentCollection(
3524 3
                            $this->em,
3525 3
                            $this->em->getClassMetadata($assoc2['targetEntity']),
3526 3
                            new ArrayCollection
3527
                        );
3528 3
                        $managedCol->setOwner($managedCopy, $assoc2);
3529 3
                        $prop->setValue($managedCopy, $managedCol);
3530
                    }
3531
3532 7
                    if ($assoc2['isCascadeMerge']) {
3533 3
                        $managedCol->initialize();
3534
3535
                        // clear and set dirty a managed collection if its not also the same collection to merge from.
3536 3
                        if ( ! $managedCol->isEmpty() && $managedCol !== $mergeCol) {
3537
                            $managedCol->unwrap()->clear();
3538
                            $managedCol->setDirty(true);
3539
3540
                            if ($assoc2['isOwningSide']
3541
                                && $assoc2['type'] == ClassMetadata::MANY_TO_MANY
3542
                                && $class->isChangeTrackingNotify()
3543
                            ) {
3544
                                $this->scheduleForDirtyCheck($managedCopy);
3545
                            }
3546
                        }
3547
                    }
3548
                }
3549
            }
3550
3551 14
            if ($class->isChangeTrackingNotify()) {
3552
                // Just treat all properties as changed, there is no other choice.
3553 14
                $this->propertyChanged($managedCopy, $name, null, $prop->getValue($managedCopy));
3554
            }
3555
        }
3556 14
    }
3557
3558
    /**
3559
     * This method called by hydrators, and indicates that hydrator totally completed current hydration cycle.
3560
     * Unit of work able to fire deferred events, related to loading events here.
3561
     *
3562
     * @internal should be called internally from object hydrators
3563
     */
3564 249
    public function hydrationComplete()
3565
    {
3566 249
        $this->hydrationCompleteHandler->hydrationComplete();
3567 249
    }
3568
3569
    /**
3570
     * @param string $entityName
3571
     */
3572 3
    private function clearIdentityMapForEntityName($entityName)
3573
    {
3574 3
        if (! isset($this->identityMap[$entityName])) {
3575
            return;
3576
        }
3577
3578 3
        $visited = [];
3579
3580 3
        foreach ($this->identityMap[$entityName] as $entity) {
3581 3
            $this->doDetach($entity, $visited, false);
3582
        }
3583 3
    }
3584
3585
    /**
3586
     * @param string $entityName
3587
     */
3588 3
    private function clearEntityInsertionsForEntityName($entityName)
3589
    {
3590 3
        foreach ($this->entityInsertions as $hash => $entity) {
3591
            // note: performance optimization - `instanceof` is much faster than a function call
3592 1
            if ($entity instanceof $entityName && get_class($entity) === $entityName) {
3593 1
                unset($this->entityInsertions[$hash]);
3594
            }
3595
        }
3596 3
    }
3597
3598
    /**
3599
     * @param ClassMetadata $class
3600
     * @param mixed         $identifierValue
3601
     *
3602
     * @return mixed the identifier after type conversion
3603
     *
3604
     * @throws \Doctrine\ORM\Mapping\MappingException if the entity has more than a single identifier
3605
     */
3606 168
    private function convertSingleFieldIdentifierToPHPValue(ClassMetadata $class, $identifierValue)
3607
    {
3608 168
        return $this->em->getConnection()->convertToPHPValue(
3609 168
            $identifierValue,
3610 168
            $class->getTypeOfField($class->getSingleIdentifierFieldName())
3611
        );
3612
    }
3613
}
3614