Passed
Pull Request — 2.6 (#7586)
by
unknown
06:35
created

UnitOfWork::afterTransactionComplete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html?highlight=eager#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 2478
    public function __construct(EntityManagerInterface $em)
303
    {
304 2478
        $this->em                         = $em;
305 2478
        $this->evm                        = $em->getEventManager();
306 2478
        $this->listenersInvoker           = new ListenersInvoker($em);
307 2478
        $this->hasCache                   = $em->getConfiguration()->isSecondLevelCacheEnabled();
308 2478
        $this->identifierFlattener        = new IdentifierFlattener($this, $em->getMetadataFactory());
309 2478
        $this->hydrationCompleteHandler   = new HydrationCompleteHandler($this->listenersInvoker, $em);
310 2478
        $this->reflectionPropertiesGetter = new ReflectionPropertiesGetter(new RuntimeReflectionService());
311 2478
    }
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 1088
    public function commit($entity = null)
333
    {
334
        // Raise preFlush
335 1088
        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 1088
        if (null === $entity) {
341 1078
            $this->computeChangeSets();
342 19
        } elseif (is_object($entity)) {
343 17
            $this->computeSingleEntityChangeSet($entity);
344 2
        } elseif (is_array($entity)) {
0 ignored issues
show
introduced by
The condition is_array($entity) is always true.
Loading history...
345 2
            foreach ($entity as $object) {
346 2
                $this->computeSingleEntityChangeSet($object);
347
            }
348
        }
349
350 1085
        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 176
                $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 139
                $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 43
                $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 39
                $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 1085
                $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 27
            $this->dispatchOnFlushEvent();
357 27
            $this->dispatchPostFlushEvent();
358
359 27
            return; // Nothing to do.
360
        }
361
362 1081
        $this->assertThatThereAreNoUnintentionallyNonPersistedAssociations();
363
364 1079
        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...
365 16
            foreach ($this->orphanRemovals as $orphan) {
366 16
                $this->remove($orphan);
367
            }
368
        }
369
370 1079
        $this->dispatchOnFlushEvent();
371
372
        // Now we need a commit order to maintain referential integrity
373 1079
        $commitOrder = $this->getCommitOrder();
374
375 1079
        $conn = $this->em->getConnection();
376 1079
        $conn->beginTransaction();
377
378
        try {
379
            // Collection deletions (deletions of complete collections)
380 1079
            foreach ($this->collectionDeletions as $collectionToDelete) {
381 19
                $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
382
            }
383
384 1079
            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...
385 1075
                foreach ($commitOrder as $class) {
386 1075
                    $this->executeInserts($class);
387
                }
388
            }
389
390 1078
            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...
391 123
                foreach ($commitOrder as $class) {
392 123
                    $this->executeUpdates($class);
393
                }
394
            }
395
396
            // Extra updates that were requested by persisters.
397 1074
            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...
398 44
                $this->executeExtraUpdates();
399
            }
400
401
            // Collection updates (deleteRows, updateRows, insertRows)
402 1074
            foreach ($this->collectionUpdates as $collectionToUpdate) {
403 543
                $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
404
            }
405
406
            // Entity deletions come last and need to be in reverse commit order
407 1074
            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...
408 64
                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...
409 64
                    $this->executeDeletions($commitOrder[$i]);
410
                }
411
            }
412
413 1074
            $conn->commit();
414 11
        } catch (Throwable $e) {
415 11
            $this->em->close();
416 11
            $conn->rollBack();
417
418 11
            $this->afterTransactionRolledBack();
419
420 11
            throw $e;
421
        }
422
423 1074
        $this->afterTransactionComplete();
424
425
        // Take new snapshots from visited collections
426 1074
        foreach ($this->visitedCollections as $coll) {
427 542
            $coll->takeSnapshot();
428
        }
429
430 1074
        $this->dispatchPostFlushEvent();
431
432 1073
        $this->postCommitCleanup($entity);
433 1073
    }
434
435
    /**
436
     * @param null|object|object[] $entity
437
     */
438 1073
    private function postCommitCleanup($entity) : void
439
    {
440 1073
        $this->entityInsertions =
441 1073
        $this->entityUpdates =
442 1073
        $this->entityDeletions =
443 1073
        $this->extraUpdates =
444 1073
        $this->collectionUpdates =
445 1073
        $this->nonCascadedNewDetectedEntities =
446 1073
        $this->collectionDeletions =
447 1073
        $this->visitedCollections =
448 1073
        $this->orphanRemovals = [];
449
450 1073
        if (null === $entity) {
451 1063
            $this->entityChangeSets = $this->scheduledForSynchronization = [];
452
453 1063
            return;
454
        }
455
456 16
        $entities = \is_object($entity)
457 14
            ? [$entity]
458 16
            : $entity;
459
460 16
        foreach ($entities as $object) {
461 16
            $oid = \spl_object_hash($object);
462
463 16
            $this->clearEntityChangeSet($oid);
464
465 16
            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...
466
        }
467 16
    }
468
469
    /**
470
     * Computes the changesets of all entities scheduled for insertion.
471
     *
472
     * @return void
473
     */
474 1087
    private function computeScheduleInsertsChangeSets()
475
    {
476 1087
        foreach ($this->entityInsertions as $entity) {
477 1079
            $class = $this->em->getClassMetadata(get_class($entity));
478
479 1079
            $this->computeChangeSet($class, $entity);
480
        }
481 1085
    }
482
483
    /**
484
     * Only flushes the given entity according to a ruleset that keeps the UoW consistent.
485
     *
486
     * 1. All entities scheduled for insertion, (orphan) removals and changes in collections are processed as well!
487
     * 2. Read Only entities are skipped.
488
     * 3. Proxies are skipped.
489
     * 4. Only if entity is properly managed.
490
     *
491
     * @param object $entity
492
     *
493
     * @return void
494
     *
495
     * @throws \InvalidArgumentException
496
     */
497 19
    private function computeSingleEntityChangeSet($entity)
498
    {
499 19
        $state = $this->getEntityState($entity);
500
501 19
        if ($state !== self::STATE_MANAGED && $state !== self::STATE_REMOVED) {
502 1
            throw new \InvalidArgumentException("Entity has to be managed or scheduled for removal for single computation " . self::objToStr($entity));
503
        }
504
505 18
        $class = $this->em->getClassMetadata(get_class($entity));
506
507 18
        if ($state === self::STATE_MANAGED && $class->isChangeTrackingDeferredImplicit()) {
508 17
            $this->persist($entity);
509
        }
510
511
        // Compute changes for INSERTed entities first. This must always happen even in this case.
512 18
        $this->computeScheduleInsertsChangeSets();
513
514 18
        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...
515
            return;
516
        }
517
518
        // Ignore uninitialized proxy objects
519 18
        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...
520 2
            return;
521
        }
522
523
        // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
524 16
        $oid = spl_object_hash($entity);
525
526 16
        if ( ! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
527 7
            $this->computeChangeSet($class, $entity);
528
        }
529 16
    }
530
531
    /**
532
     * Executes any extra updates that have been scheduled.
533
     */
534 44
    private function executeExtraUpdates()
535
    {
536 44
        foreach ($this->extraUpdates as $oid => $update) {
537 44
            list ($entity, $changeset) = $update;
538
539 44
            $this->entityChangeSets[$oid] = $changeset;
540 44
            $this->getEntityPersister(get_class($entity))->update($entity);
541
        }
542
543 44
        $this->extraUpdates = [];
544 44
    }
545
546
    /**
547
     * Gets the changeset for an entity.
548
     *
549
     * @param object $entity
550
     *
551
     * @return array
552
     */
553 1073
    public function & getEntityChangeSet($entity)
554
    {
555 1073
        $oid  = spl_object_hash($entity);
556 1073
        $data = [];
557
558 1073
        if (!isset($this->entityChangeSets[$oid])) {
559 4
            return $data;
560
        }
561
562 1073
        return $this->entityChangeSets[$oid];
563
    }
564
565
    /**
566
     * Computes the changes that happened to a single entity.
567
     *
568
     * Modifies/populates the following properties:
569
     *
570
     * {@link _originalEntityData}
571
     * If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
572
     * then it was not fetched from the database and therefore we have no original
573
     * entity data yet. All of the current entity data is stored as the original entity data.
574
     *
575
     * {@link _entityChangeSets}
576
     * The changes detected on all properties of the entity are stored there.
577
     * A change is a tuple array where the first entry is the old value and the second
578
     * entry is the new value of the property. Changesets are used by persisters
579
     * to INSERT/UPDATE the persistent entity state.
580
     *
581
     * {@link _entityUpdates}
582
     * If the entity is already fully MANAGED (has been fetched from the database before)
583
     * and any changes to its properties are detected, then a reference to the entity is stored
584
     * there to mark it for an update.
585
     *
586
     * {@link _collectionDeletions}
587
     * If a PersistentCollection has been de-referenced in a fully MANAGED entity,
588
     * then this collection is marked for deletion.
589
     *
590
     * @ignore
591
     *
592
     * @internal Don't call from the outside.
593
     *
594
     * @param ClassMetadata $class  The class descriptor of the entity.
595
     * @param object        $entity The entity for which to compute the changes.
596
     *
597
     * @return void
598
     */
599 1089
    public function computeChangeSet(ClassMetadata $class, $entity)
600
    {
601 1089
        $oid = spl_object_hash($entity);
602
603 1089
        if (isset($this->readOnlyObjects[$oid])) {
604 2
            return;
605
        }
606
607 1089
        if ( ! $class->isInheritanceTypeNone()) {
608 337
            $class = $this->em->getClassMetadata(get_class($entity));
609
        }
610
611 1089
        $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preFlush) & ~ListenersInvoker::INVOKE_MANAGER;
612
613 1089
        if ($invoke !== ListenersInvoker::INVOKE_NONE) {
614 138
            $this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke);
615
        }
616
617 1089
        $actualData = [];
618
619 1089
        foreach ($class->reflFields as $name => $refProp) {
620 1089
            $value = $refProp->getValue($entity);
621
622 1089
            if ($class->isCollectionValuedAssociation($name) && $value !== null) {
623 815
                if ($value instanceof PersistentCollection) {
624 205
                    if ($value->getOwner() === $entity) {
625 205
                        continue;
626
                    }
627
628 5
                    $value = new ArrayCollection($value->getValues());
629
                }
630
631
                // If $value is not a Collection then use an ArrayCollection.
632 810
                if ( ! $value instanceof Collection) {
633 243
                    $value = new ArrayCollection($value);
634
                }
635
636 810
                $assoc = $class->associationMappings[$name];
637
638
                // Inject PersistentCollection
639 810
                $value = new PersistentCollection(
640 810
                    $this->em, $this->em->getClassMetadata($assoc['targetEntity']), $value
641
                );
642 810
                $value->setOwner($entity, $assoc);
643 810
                $value->setDirty( ! $value->isEmpty());
644
645 810
                $class->reflFields[$name]->setValue($entity, $value);
646
647 810
                $actualData[$name] = $value;
648
649 810
                continue;
650
            }
651
652 1089
            if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) && ($name !== $class->versionField)) {
653 1089
                $actualData[$name] = $value;
654
            }
655
        }
656
657 1089
        if ( ! isset($this->originalEntityData[$oid])) {
658
            // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
659
            // These result in an INSERT.
660 1085
            $this->originalEntityData[$oid] = $actualData;
661 1085
            $changeSet = [];
662
663 1085
            foreach ($actualData as $propName => $actualValue) {
664 1062
                if ( ! isset($class->associationMappings[$propName])) {
665 1005
                    $changeSet[$propName] = [null, $actualValue];
666
667 1005
                    continue;
668
                }
669
670 944
                $assoc = $class->associationMappings[$propName];
671
672 944
                if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
673 944
                    $changeSet[$propName] = [null, $actualValue];
674
                }
675
            }
676
677 1085
            $this->entityChangeSets[$oid] = $changeSet;
678
        } else {
679
            // Entity is "fully" MANAGED: it was already fully persisted before
680
            // and we have a copy of the original data
681 278
            $originalData           = $this->originalEntityData[$oid];
682 278
            $isChangeTrackingNotify = $class->isChangeTrackingNotify();
683 278
            $changeSet              = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
684
                ? $this->entityChangeSets[$oid]
685 278
                : [];
686
687 278
            foreach ($actualData as $propName => $actualValue) {
688
                // skip field, its a partially omitted one!
689 262
                if ( ! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
690 8
                    continue;
691
                }
692
693 262
                $orgValue = $originalData[$propName];
694
695
                // skip if value haven't changed
696 262
                if (is_object($orgValue) &&
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (is_object($orgValue) &&...gValue === $actualValue, Probably Intended Meaning: is_object($orgValue) && ...Value === $actualValue)
Loading history...
697 262
                    is_object($actualValue) &&
698 122
                    $orgValue == $actualValue ||
699 262
                    $orgValue === $actualValue
700
                ) {
701 245
                    continue;
702
                }
703
704
                // if regular field
705 119
                if ( ! isset($class->associationMappings[$propName])) {
706 64
                    if ($isChangeTrackingNotify) {
707
                        continue;
708
                    }
709
710 64
                    $changeSet[$propName] = [$orgValue, $actualValue];
711
712 64
                    continue;
713
                }
714
715 59
                $assoc = $class->associationMappings[$propName];
716
717
                // Persistent collection was exchanged with the "originally"
718
                // created one. This can only mean it was cloned and replaced
719
                // on another entity.
720 59
                if ($actualValue instanceof PersistentCollection) {
721 8
                    $owner = $actualValue->getOwner();
722 8
                    if ($owner === null) { // cloned
723
                        $actualValue->setOwner($entity, $assoc);
724 8
                    } else if ($owner !== $entity) { // no clone, we have to fix
725
                        if (!$actualValue->isInitialized()) {
726
                            $actualValue->initialize(); // we have to do this otherwise the cols share state
727
                        }
728
                        $newValue = clone $actualValue;
729
                        $newValue->setOwner($entity, $assoc);
730
                        $class->reflFields[$propName]->setValue($entity, $newValue);
731
                    }
732
                }
733
734 59
                if ($orgValue instanceof PersistentCollection) {
735
                    // A PersistentCollection was de-referenced, so delete it.
736 8
                    $coid = spl_object_hash($orgValue);
737
738 8
                    if (isset($this->collectionDeletions[$coid])) {
739
                        continue;
740
                    }
741
742 8
                    $this->collectionDeletions[$coid] = $orgValue;
743 8
                    $changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored.
744
745 8
                    continue;
746
                }
747
748 51
                if ($assoc['type'] & ClassMetadata::TO_ONE) {
749 50
                    if ($assoc['isOwningSide']) {
750 22
                        $changeSet[$propName] = [$orgValue, $actualValue];
751
                    }
752
753 50
                    if ($orgValue !== null && $assoc['orphanRemoval']) {
754 51
                        $this->scheduleOrphanRemoval($orgValue);
755
                    }
756
                }
757
            }
758
759 278
            if ($changeSet) {
760 92
                $this->entityChangeSets[$oid]   = $changeSet;
761 92
                $this->originalEntityData[$oid] = $actualData;
762 92
                $this->entityUpdates[$oid]      = $entity;
763
            }
764
        }
765
766
        // Look for changes in associations of the entity
767 1089
        foreach ($class->associationMappings as $field => $assoc) {
768 944
            if (($val = $class->reflFields[$field]->getValue($entity)) === null) {
769 663
                continue;
770
            }
771
772 915
            $this->computeAssociationChanges($assoc, $val);
773
774 907
            if ( ! isset($this->entityChangeSets[$oid]) &&
775 907
                $assoc['isOwningSide'] &&
776 907
                $assoc['type'] == ClassMetadata::MANY_TO_MANY &&
777 907
                $val instanceof PersistentCollection &&
778 907
                $val->isDirty()) {
779
780 35
                $this->entityChangeSets[$oid]   = [];
781 35
                $this->originalEntityData[$oid] = $actualData;
782 907
                $this->entityUpdates[$oid]      = $entity;
783
            }
784
        }
785 1081
    }
786
787
    /**
788
     * Computes all the changes that have been done to entities and collections
789
     * since the last commit and stores these changes in the _entityChangeSet map
790
     * temporarily for access by the persisters, until the UoW commit is finished.
791
     *
792
     * @return void
793
     */
794 1078
    public function computeChangeSets()
795
    {
796
        // Compute changes for INSERTed entities first. This must always happen.
797 1078
        $this->computeScheduleInsertsChangeSets();
798
799
        // Compute changes for other MANAGED entities. Change tracking policies take effect here.
800 1076
        foreach ($this->identityMap as $className => $entities) {
801 472
            $class = $this->em->getClassMetadata($className);
802
803
            // Skip class if instances are read-only
804 472
            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...
805 1
                continue;
806
            }
807
808
            // If change tracking is explicit or happens through notification, then only compute
809
            // changes on entities of that type that are explicitly marked for synchronization.
810
            switch (true) {
811 471
                case ($class->isChangeTrackingDeferredImplicit()):
812 469
                    $entitiesToProcess = $entities;
813 469
                    break;
814
815 3
                case (isset($this->scheduledForSynchronization[$className])):
816 3
                    $entitiesToProcess = $this->scheduledForSynchronization[$className];
817 3
                    break;
818
819
                default:
820 1
                    $entitiesToProcess = [];
821
822
            }
823
824 471
            foreach ($entitiesToProcess as $entity) {
825
                // Ignore uninitialized proxy objects
826 451
                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...
827 37
                    continue;
828
                }
829
830
                // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
831 450
                $oid = spl_object_hash($entity);
832
833 450
                if ( ! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
834 471
                    $this->computeChangeSet($class, $entity);
835
                }
836
            }
837
        }
838 1076
    }
839
840
    /**
841
     * Computes the changes of an association.
842
     *
843
     * @param array $assoc The association mapping.
844
     * @param mixed $value The value of the association.
845
     *
846
     * @throws ORMInvalidArgumentException
847
     * @throws ORMException
848
     *
849
     * @return void
850
     */
851 915
    private function computeAssociationChanges($assoc, $value)
852
    {
853 915
        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...
854 30
            return;
855
        }
856
857 914
        if ($value instanceof PersistentCollection && $value->isDirty()) {
858 547
            $coid = spl_object_hash($value);
859
860 547
            $this->collectionUpdates[$coid] = $value;
861 547
            $this->visitedCollections[$coid] = $value;
862
        }
863
864
        // Look through the entities, and in any of their associations,
865
        // for transient (new) entities, recursively. ("Persistence by reachability")
866
        // Unwrap. Uninitialized collections will simply be empty.
867 914
        $unwrappedValue = ($assoc['type'] & ClassMetadata::TO_ONE) ? [$value] : $value->unwrap();
868 914
        $targetClass    = $this->em->getClassMetadata($assoc['targetEntity']);
869
870 914
        foreach ($unwrappedValue as $key => $entry) {
871 754
            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...
872 8
                throw ORMInvalidArgumentException::invalidAssociation($targetClass, $assoc, $entry);
873
            }
874
875 746
            $state = $this->getEntityState($entry, self::STATE_NEW);
876
877 746
            if ( ! ($entry instanceof $assoc['targetEntity'])) {
878
                throw ORMException::unexpectedAssociationValue($assoc['sourceEntity'], $assoc['fieldName'], get_class($entry), $assoc['targetEntity']);
879
            }
880
881
            switch ($state) {
882 746
                case self::STATE_NEW:
883 42
                    if ( ! $assoc['isCascadePersist']) {
884
                        /*
885
                         * For now just record the details, because this may
886
                         * not be an issue if we later discover another pathway
887
                         * through the object-graph where cascade-persistence
888
                         * is enabled for this object.
889
                         */
890 6
                        $this->nonCascadedNewDetectedEntities[\spl_object_hash($entry)] = [$assoc, $entry];
891
892 6
                        break;
893
                    }
894
895 37
                    $this->persistNew($targetClass, $entry);
896 37
                    $this->computeChangeSet($targetClass, $entry);
897
898 37
                    break;
899
900 738
                case self::STATE_REMOVED:
901
                    // Consume the $value as array (it's either an array or an ArrayAccess)
902
                    // and remove the element from Collection.
903 4
                    if ($assoc['type'] & ClassMetadata::TO_MANY) {
904 3
                        unset($value[$key]);
905
                    }
906 4
                    break;
907
908 738
                case self::STATE_DETACHED:
909
                    // Can actually not happen right now as we assume STATE_NEW,
910
                    // so the exception will be raised from the DBAL layer (constraint violation).
911
                    throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($assoc, $entry);
912
                    break;
913
914 746
                default:
915
                    // MANAGED associated entities are already taken into account
916
                    // during changeset calculation anyway, since they are in the identity map.
917
            }
918
        }
919 906
    }
920
921
    /**
922
     * @param \Doctrine\ORM\Mapping\ClassMetadata $class
923
     * @param object                              $entity
924
     *
925
     * @return void
926
     */
927 1108
    private function persistNew($class, $entity)
928
    {
929 1108
        $oid    = spl_object_hash($entity);
930 1108
        $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::prePersist);
931
932 1108
        if ($invoke !== ListenersInvoker::INVOKE_NONE) {
933 141
            $this->listenersInvoker->invoke($class, Events::prePersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
934
        }
935
936 1108
        $idGen = $class->idGenerator;
937
938 1108
        if ( ! $idGen->isPostInsertGenerator()) {
939 290
            $idValue = $idGen->generate($this->em, $entity);
940
941 290
            if ( ! $idGen instanceof \Doctrine\ORM\Id\AssignedGenerator) {
942 2
                $idValue = [$class->getSingleIdentifierFieldName() => $this->convertSingleFieldIdentifierToPHPValue($class, $idValue)];
943
944 2
                $class->setIdentifierValues($entity, $idValue);
945
            }
946
947
            // Some identifiers may be foreign keys to new entities.
948
            // In this case, we don't have the value yet and should treat it as if we have a post-insert generator
949 290
            if (! $this->hasMissingIdsWhichAreForeignKeys($class, $idValue)) {
950 287
                $this->entityIdentifiers[$oid] = $idValue;
951
            }
952
        }
953
954 1108
        $this->entityStates[$oid] = self::STATE_MANAGED;
955
956 1108
        $this->scheduleForInsert($entity);
957 1108
    }
958
959
    /**
960
     * @param mixed[] $idValue
961
     */
962 290
    private function hasMissingIdsWhichAreForeignKeys(ClassMetadata $class, array $idValue) : bool
963
    {
964 290
        foreach ($idValue as $idField => $idFieldValue) {
965 290
            if ($idFieldValue === null && isset($class->associationMappings[$idField])) {
966 290
                return true;
967
            }
968
        }
969
970 287
        return false;
971
    }
972
973
    /**
974
     * INTERNAL:
975
     * Computes the changeset of an individual entity, independently of the
976
     * computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
977
     *
978
     * The passed entity must be a managed entity. If the entity already has a change set
979
     * because this method is invoked during a commit cycle then the change sets are added.
980
     * whereby changes detected in this method prevail.
981
     *
982
     * @ignore
983
     *
984
     * @param ClassMetadata $class  The class descriptor of the entity.
985
     * @param object        $entity The entity for which to (re)calculate the change set.
986
     *
987
     * @return void
988
     *
989
     * @throws ORMInvalidArgumentException If the passed entity is not MANAGED.
990
     */
991 16
    public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity)
992
    {
993 16
        $oid = spl_object_hash($entity);
994
995 16
        if ( ! isset($this->entityStates[$oid]) || $this->entityStates[$oid] != self::STATE_MANAGED) {
996
            throw ORMInvalidArgumentException::entityNotManaged($entity);
997
        }
998
999
        // skip if change tracking is "NOTIFY"
1000 16
        if ($class->isChangeTrackingNotify()) {
1001
            return;
1002
        }
1003
1004 16
        if ( ! $class->isInheritanceTypeNone()) {
1005 3
            $class = $this->em->getClassMetadata(get_class($entity));
1006
        }
1007
1008 16
        $actualData = [];
1009
1010 16
        foreach ($class->reflFields as $name => $refProp) {
1011 16
            if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity())
1012 16
                && ($name !== $class->versionField)
1013 16
                && ! $class->isCollectionValuedAssociation($name)) {
1014 16
                $actualData[$name] = $refProp->getValue($entity);
1015
            }
1016
        }
1017
1018 16
        if ( ! isset($this->originalEntityData[$oid])) {
1019
            throw new \RuntimeException('Cannot call recomputeSingleEntityChangeSet before computeChangeSet on an entity.');
1020
        }
1021
1022 16
        $originalData = $this->originalEntityData[$oid];
1023 16
        $changeSet = [];
1024
1025 16
        foreach ($actualData as $propName => $actualValue) {
1026 16
            $orgValue = $originalData[$propName] ?? null;
1027
1028 16
            if ($orgValue !== $actualValue) {
1029 16
                $changeSet[$propName] = [$orgValue, $actualValue];
1030
            }
1031
        }
1032
1033 16
        if ($changeSet) {
1034 7
            if (isset($this->entityChangeSets[$oid])) {
1035 6
                $this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
1036 1
            } else if ( ! isset($this->entityInsertions[$oid])) {
1037 1
                $this->entityChangeSets[$oid] = $changeSet;
1038 1
                $this->entityUpdates[$oid]    = $entity;
1039
            }
1040 7
            $this->originalEntityData[$oid] = $actualData;
1041
        }
1042 16
    }
1043
1044
    /**
1045
     * Executes all entity insertions for entities of the specified type.
1046
     *
1047
     * @param \Doctrine\ORM\Mapping\ClassMetadata $class
1048
     *
1049
     * @return void
1050
     */
1051 1075
    private function executeInserts($class)
1052
    {
1053 1075
        $entities   = [];
1054 1075
        $className  = $class->name;
1055 1075
        $persister  = $this->getEntityPersister($className);
1056 1075
        $invoke     = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist);
1057
1058 1075
        $insertionsForClass = [];
1059
1060 1075
        foreach ($this->entityInsertions as $oid => $entity) {
1061
1062 1075
            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...
1063 907
                continue;
1064
            }
1065
1066 1075
            $insertionsForClass[$oid] = $entity;
1067
1068 1075
            $persister->addInsert($entity);
1069
1070 1075
            unset($this->entityInsertions[$oid]);
1071
1072 1075
            if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1073 1075
                $entities[] = $entity;
1074
            }
1075
        }
1076
1077 1075
        $postInsertIds = $persister->executeInserts();
1078
1079 1075
        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...
1080
            // Persister returned post-insert IDs
1081 974
            foreach ($postInsertIds as $postInsertId) {
1082 974
                $idField = $class->getSingleIdentifierFieldName();
1083 974
                $idValue = $this->convertSingleFieldIdentifierToPHPValue($class, $postInsertId['generatedId']);
1084
1085 974
                $entity  = $postInsertId['entity'];
1086 974
                $oid     = spl_object_hash($entity);
1087
1088 974
                $class->reflFields[$idField]->setValue($entity, $idValue);
1089
1090 974
                $this->entityIdentifiers[$oid] = [$idField => $idValue];
1091 974
                $this->entityStates[$oid] = self::STATE_MANAGED;
1092 974
                $this->originalEntityData[$oid][$idField] = $idValue;
1093
1094 974
                $this->addToIdentityMap($entity);
1095
            }
1096
        } else {
1097 815
            foreach ($insertionsForClass as $oid => $entity) {
1098 277
                if (! isset($this->entityIdentifiers[$oid])) {
1099
                    //entity was not added to identity map because some identifiers are foreign keys to new entities.
1100
                    //add it now
1101 277
                    $this->addToEntityIdentifiersAndEntityMap($class, $oid, $entity);
1102
                }
1103
            }
1104
        }
1105
1106 1075
        foreach ($entities as $entity) {
1107 136
            $this->listenersInvoker->invoke($class, Events::postPersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
1108
        }
1109 1075
    }
1110
1111
    /**
1112
     * @param object $entity
1113
     */
1114 3
    private function addToEntityIdentifiersAndEntityMap(ClassMetadata $class, string $oid, $entity): void
1115
    {
1116 3
        $identifier = [];
1117
1118 3
        foreach ($class->getIdentifierFieldNames() as $idField) {
1119 3
            $value = $class->getFieldValue($entity, $idField);
1120
1121 3
            if (isset($class->associationMappings[$idField])) {
1122
                // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced.
1123 3
                $value = $this->getSingleIdentifierValue($value);
1124
            }
1125
1126 3
            $identifier[$idField] = $this->originalEntityData[$oid][$idField] = $value;
1127
        }
1128
1129 3
        $this->entityStates[$oid]      = self::STATE_MANAGED;
1130 3
        $this->entityIdentifiers[$oid] = $identifier;
1131
1132 3
        $this->addToIdentityMap($entity);
1133 3
    }
1134
1135
    /**
1136
     * Executes all entity updates for entities of the specified type.
1137
     *
1138
     * @param \Doctrine\ORM\Mapping\ClassMetadata $class
1139
     *
1140
     * @return void
1141
     */
1142 123
    private function executeUpdates($class)
1143
    {
1144 123
        $className          = $class->name;
1145 123
        $persister          = $this->getEntityPersister($className);
1146 123
        $preUpdateInvoke    = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate);
1147 123
        $postUpdateInvoke   = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate);
1148
1149 123
        foreach ($this->entityUpdates as $oid => $entity) {
1150 123
            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...
1151 79
                continue;
1152
            }
1153
1154 123
            if ($preUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
1155 13
                $this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->getEntityChangeSet($entity)), $preUpdateInvoke);
1156
1157 13
                $this->recomputeSingleEntityChangeSet($class, $entity);
1158
            }
1159
1160 123
            if ( ! empty($this->entityChangeSets[$oid])) {
1161 89
                $persister->update($entity);
1162
            }
1163
1164 119
            unset($this->entityUpdates[$oid]);
1165
1166 119
            if ($postUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
1167 119
                $this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke);
1168
            }
1169
        }
1170 119
    }
1171
1172
    /**
1173
     * Executes all entity deletions for entities of the specified type.
1174
     *
1175
     * @param \Doctrine\ORM\Mapping\ClassMetadata $class
1176
     *
1177
     * @return void
1178
     */
1179 64
    private function executeDeletions($class)
1180
    {
1181 64
        $className  = $class->name;
1182 64
        $persister  = $this->getEntityPersister($className);
1183 64
        $invoke     = $this->listenersInvoker->getSubscribedSystems($class, Events::postRemove);
1184
1185 64
        foreach ($this->entityDeletions as $oid => $entity) {
1186 64
            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...
1187 26
                continue;
1188
            }
1189
1190 64
            $persister->delete($entity);
1191
1192
            unset(
1193 64
                $this->entityDeletions[$oid],
1194 64
                $this->entityIdentifiers[$oid],
1195 64
                $this->originalEntityData[$oid],
1196 64
                $this->entityStates[$oid]
1197
            );
1198
1199
            // Entity with this $oid after deletion treated as NEW, even if the $oid
1200
            // is obtained by a new entity because the old one went out of scope.
1201
            //$this->entityStates[$oid] = self::STATE_NEW;
1202 64
            if ( ! $class->isIdentifierNatural()) {
1203 53
                $class->reflFields[$class->identifier[0]]->setValue($entity, null);
1204
            }
1205
1206 64
            if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1207 64
                $this->listenersInvoker->invoke($class, Events::postRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
1208
            }
1209
        }
1210 63
    }
1211
1212
    /**
1213
     * Gets the commit order.
1214
     *
1215
     * @param array|null $entityChangeSet
1216
     *
1217
     * @return array
1218
     */
1219 1079
    private function getCommitOrder(array $entityChangeSet = null)
1220
    {
1221 1079
        if ($entityChangeSet === null) {
1222 1079
            $entityChangeSet = array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions);
1223
        }
1224
1225 1079
        $calc = $this->getCommitOrderCalculator();
1226
1227
        // See if there are any new classes in the changeset, that are not in the
1228
        // commit order graph yet (don't have a node).
1229
        // We have to inspect changeSet to be able to correctly build dependencies.
1230
        // It is not possible to use IdentityMap here because post inserted ids
1231
        // are not yet available.
1232 1079
        $newNodes = [];
1233
1234 1079
        foreach ($entityChangeSet as $entity) {
1235 1079
            $class = $this->em->getClassMetadata(get_class($entity));
1236
1237 1079
            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...
1238 658
                continue;
1239
            }
1240
1241 1079
            $calc->addNode($class->name, $class);
1242
1243 1079
            $newNodes[] = $class;
1244
        }
1245
1246
        // Calculate dependencies for new nodes
1247 1079
        while ($class = array_pop($newNodes)) {
1248 1079
            foreach ($class->associationMappings as $assoc) {
1249 933
                if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
1250 885
                    continue;
1251
                }
1252
1253 883
                $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
1254
1255 883
                if ( ! $calc->hasNode($targetClass->name)) {
1256 681
                    $calc->addNode($targetClass->name, $targetClass);
1257
1258 681
                    $newNodes[] = $targetClass;
1259
                }
1260
1261 883
                $joinColumns = reset($assoc['joinColumns']);
1262
1263 883
                $calc->addDependency($targetClass->name, $class->name, (int)empty($joinColumns['nullable']));
1264
1265
                // If the target class has mapped subclasses, these share the same dependency.
1266 883
                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...
1267 876
                    continue;
1268
                }
1269
1270 238
                foreach ($targetClass->subClasses as $subClassName) {
1271 238
                    $targetSubClass = $this->em->getClassMetadata($subClassName);
1272
1273 238
                    if ( ! $calc->hasNode($subClassName)) {
1274 208
                        $calc->addNode($targetSubClass->name, $targetSubClass);
1275
1276 208
                        $newNodes[] = $targetSubClass;
1277
                    }
1278
1279 238
                    $calc->addDependency($targetSubClass->name, $class->name, 1);
1280
                }
1281
            }
1282
        }
1283
1284 1079
        return $calc->sort();
1285
    }
1286
1287
    /**
1288
     * Schedules an entity for insertion into the database.
1289
     * If the entity already has an identifier, it will be added to the identity map.
1290
     *
1291
     * @param object $entity The entity to schedule for insertion.
1292
     *
1293
     * @return void
1294
     *
1295
     * @throws ORMInvalidArgumentException
1296
     * @throws \InvalidArgumentException
1297
     */
1298 1109
    public function scheduleForInsert($entity)
1299
    {
1300 1109
        $oid = spl_object_hash($entity);
1301
1302 1109
        if (isset($this->entityUpdates[$oid])) {
1303
            throw new InvalidArgumentException("Dirty entity can not be scheduled for insertion.");
1304
        }
1305
1306 1109
        if (isset($this->entityDeletions[$oid])) {
1307 1
            throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
1308
        }
1309 1109
        if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
1310 1
            throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
1311
        }
1312
1313 1109
        if (isset($this->entityInsertions[$oid])) {
1314 1
            throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
1315
        }
1316
1317 1109
        $this->entityInsertions[$oid] = $entity;
1318
1319 1109
        if (isset($this->entityIdentifiers[$oid])) {
1320 287
            $this->addToIdentityMap($entity);
1321
        }
1322
1323 1109
        if ($entity instanceof NotifyPropertyChanged) {
1324 8
            $entity->addPropertyChangedListener($this);
1325
        }
1326 1109
    }
1327
1328
    /**
1329
     * Checks whether an entity is scheduled for insertion.
1330
     *
1331
     * @param object $entity
1332
     *
1333
     * @return boolean
1334
     */
1335 655
    public function isScheduledForInsert($entity)
1336
    {
1337 655
        return isset($this->entityInsertions[spl_object_hash($entity)]);
1338
    }
1339
1340
    /**
1341
     * Schedules an entity for being updated.
1342
     *
1343
     * @param object $entity The entity to schedule for being updated.
1344
     *
1345
     * @return void
1346
     *
1347
     * @throws ORMInvalidArgumentException
1348
     */
1349 1
    public function scheduleForUpdate($entity)
1350
    {
1351 1
        $oid = spl_object_hash($entity);
1352
1353 1
        if ( ! isset($this->entityIdentifiers[$oid])) {
1354
            throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "scheduling for update");
1355
        }
1356
1357 1
        if (isset($this->entityDeletions[$oid])) {
1358
            throw ORMInvalidArgumentException::entityIsRemoved($entity, "schedule for update");
1359
        }
1360
1361 1
        if ( ! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
1362 1
            $this->entityUpdates[$oid] = $entity;
1363
        }
1364 1
    }
1365
1366
    /**
1367
     * INTERNAL:
1368
     * Schedules an extra update that will be executed immediately after the
1369
     * regular entity updates within the currently running commit cycle.
1370
     *
1371
     * Extra updates for entities are stored as (entity, changeset) tuples.
1372
     *
1373
     * @ignore
1374
     *
1375
     * @param object $entity    The entity for which to schedule an extra update.
1376
     * @param array  $changeset The changeset of the entity (what to update).
1377
     *
1378
     * @return void
1379
     */
1380 44
    public function scheduleExtraUpdate($entity, array $changeset)
1381
    {
1382 44
        $oid         = spl_object_hash($entity);
1383 44
        $extraUpdate = [$entity, $changeset];
1384
1385 44
        if (isset($this->extraUpdates[$oid])) {
1386 1
            list(, $changeset2) = $this->extraUpdates[$oid];
1387
1388 1
            $extraUpdate = [$entity, $changeset + $changeset2];
1389
        }
1390
1391 44
        $this->extraUpdates[$oid] = $extraUpdate;
1392 44
    }
1393
1394
    /**
1395
     * Checks whether an entity is registered as dirty in the unit of work.
1396
     * Note: Is not very useful currently as dirty entities are only registered
1397
     * at commit time.
1398
     *
1399
     * @param object $entity
1400
     *
1401
     * @return boolean
1402
     */
1403
    public function isScheduledForUpdate($entity)
1404
    {
1405
        return isset($this->entityUpdates[spl_object_hash($entity)]);
1406
    }
1407
1408
    /**
1409
     * Checks whether an entity is registered to be checked in the unit of work.
1410
     *
1411
     * @param object $entity
1412
     *
1413
     * @return boolean
1414
     */
1415 2
    public function isScheduledForDirtyCheck($entity)
1416
    {
1417 2
        $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...
1418
1419 2
        return isset($this->scheduledForSynchronization[$rootEntityName][spl_object_hash($entity)]);
1420
    }
1421
1422
    /**
1423
     * INTERNAL:
1424
     * Schedules an entity for deletion.
1425
     *
1426
     * @param object $entity
1427
     *
1428
     * @return void
1429
     */
1430 67
    public function scheduleForDelete($entity)
1431
    {
1432 67
        $oid = spl_object_hash($entity);
1433
1434 67
        if (isset($this->entityInsertions[$oid])) {
1435 1
            if ($this->isInIdentityMap($entity)) {
1436
                $this->removeFromIdentityMap($entity);
1437
            }
1438
1439 1
            unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
1440
1441 1
            return; // entity has not been persisted yet, so nothing more to do.
1442
        }
1443
1444 67
        if ( ! $this->isInIdentityMap($entity)) {
1445 1
            return;
1446
        }
1447
1448 66
        $this->removeFromIdentityMap($entity);
1449
1450 66
        unset($this->entityUpdates[$oid]);
1451
1452 66
        if ( ! isset($this->entityDeletions[$oid])) {
1453 66
            $this->entityDeletions[$oid] = $entity;
1454 66
            $this->entityStates[$oid]    = self::STATE_REMOVED;
1455
        }
1456 66
    }
1457
1458
    /**
1459
     * Checks whether an entity is registered as removed/deleted with the unit
1460
     * of work.
1461
     *
1462
     * @param object $entity
1463
     *
1464
     * @return boolean
1465
     */
1466 17
    public function isScheduledForDelete($entity)
1467
    {
1468 17
        return isset($this->entityDeletions[spl_object_hash($entity)]);
1469
    }
1470
1471
    /**
1472
     * Checks whether an entity is scheduled for insertion, update or deletion.
1473
     *
1474
     * @param object $entity
1475
     *
1476
     * @return boolean
1477
     */
1478
    public function isEntityScheduled($entity)
1479
    {
1480
        $oid = spl_object_hash($entity);
1481
1482
        return isset($this->entityInsertions[$oid])
1483
            || isset($this->entityUpdates[$oid])
1484
            || isset($this->entityDeletions[$oid]);
1485
    }
1486
1487
    /**
1488
     * INTERNAL:
1489
     * Registers an entity in the identity map.
1490
     * Note that entities in a hierarchy are registered with the class name of
1491
     * the root entity.
1492
     *
1493
     * @ignore
1494
     *
1495
     * @param object $entity The entity to register.
1496
     *
1497
     * @return boolean TRUE if the registration was successful, FALSE if the identity of
1498
     *                 the entity in question is already managed.
1499
     *
1500
     * @throws ORMInvalidArgumentException
1501
     */
1502 1173
    public function addToIdentityMap($entity)
1503
    {
1504 1173
        $classMetadata = $this->em->getClassMetadata(get_class($entity));
1505 1173
        $identifier    = $this->entityIdentifiers[spl_object_hash($entity)];
1506
1507 1173
        if (empty($identifier) || in_array(null, $identifier, true)) {
1508 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...
1509
        }
1510
1511 1167
        $idHash    = implode(' ', $identifier);
1512 1167
        $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...
1513
1514 1167
        if (isset($this->identityMap[$className][$idHash])) {
1515 86
            return false;
1516
        }
1517
1518 1167
        $this->identityMap[$className][$idHash] = $entity;
1519
1520 1167
        return true;
1521
    }
1522
1523
    /**
1524
     * Gets the state of an entity with regard to the current unit of work.
1525
     *
1526
     * @param object   $entity
1527
     * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
1528
     *                         This parameter can be set to improve performance of entity state detection
1529
     *                         by potentially avoiding a database lookup if the distinction between NEW and DETACHED
1530
     *                         is either known or does not matter for the caller of the method.
1531
     *
1532
     * @return int The entity state.
1533
     */
1534 1123
    public function getEntityState($entity, $assume = null)
1535
    {
1536 1123
        $oid = spl_object_hash($entity);
1537
1538 1123
        if (isset($this->entityStates[$oid])) {
1539 818
            return $this->entityStates[$oid];
1540
        }
1541
1542 1117
        if ($assume !== null) {
1543 1113
            return $assume;
1544
        }
1545
1546
        // State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
1547
        // Note that you can not remember the NEW or DETACHED state in _entityStates since
1548
        // the UoW does not hold references to such objects and the object hash can be reused.
1549
        // More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
1550 13
        $class = $this->em->getClassMetadata(get_class($entity));
1551 13
        $id    = $class->getIdentifierValues($entity);
1552
1553 13
        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...
1554 5
            return self::STATE_NEW;
1555
        }
1556
1557 10
        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...
1558 1
            $id = $this->identifierFlattener->flattenIdentifier($class, $id);
1559
        }
1560
1561
        switch (true) {
1562 10
            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

1562
            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...
1563
                // Check for a version field, if available, to avoid a db lookup.
1564 5
                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...
1565 1
                    return ($class->getFieldValue($entity, $class->versionField))
0 ignored issues
show
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

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

1936
                    if ($this->getEntityState(/** @scrutinizer ignore-type */ $managedCopy) == self::STATE_REMOVED) {
Loading history...
1937 15
                        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

1937
                        throw ORMInvalidArgumentException::entityIsRemoved(/** @scrutinizer ignore-type */ $managedCopy, "merge");
Loading history...
1938
                    }
1939
                } else {
1940
                    // We need to fetch the managed copy in order to merge.
1941 25
                    $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...
1942
                }
1943
1944 37
                if ($managedCopy === null) {
1945
                    // If the identifier is ASSIGNED, it is NEW, otherwise an error
1946
                    // since the managed entity was not found.
1947 3
                    if ( ! $class->isIdentifierNatural()) {
1948 1
                        throw EntityNotFoundException::fromClassNameAndIdentifier(
1949 1
                            $class->getName(),
1950 1
                            $this->identifierFlattener->flattenIdentifier($class, $id)
1951
                        );
1952
                    }
1953
1954 2
                    $managedCopy = $this->newInstance($class);
1955 2
                    $class->setIdentifierValues($managedCopy, $id);
1956
1957 2
                    $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy);
1958 2
                    $this->persistNew($class, $managedCopy);
1959
                } else {
1960 34
                    $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

1960
                    $this->ensureVersionMatch($class, $entity, /** @scrutinizer ignore-type */ $managedCopy);
Loading history...
1961 33
                    $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

1961
                    $this->mergeEntityStateIntoManagedCopy($entity, /** @scrutinizer ignore-type */ $managedCopy);
Loading history...
1962
                }
1963
            }
1964
1965 40
            $visited[$oid] = $managedCopy; // mark visited
1966
1967 40
            if ($class->isChangeTrackingDeferredExplicit()) {
1968
                $this->scheduleForDirtyCheck($entity);
1969
            }
1970
        }
1971
1972 41
        if ($prevManagedCopy !== null) {
1973 6
            $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

1973
            $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, /** @scrutinizer ignore-type */ $managedCopy);
Loading history...
1974
        }
1975
1976
        // Mark the managed copy visited as well
1977 41
        $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

1977
        $visited[spl_object_hash(/** @scrutinizer ignore-type */ $managedCopy)] = $managedCopy;
Loading history...
1978
1979 41
        $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

1979
        $this->cascadeMerge($entity, /** @scrutinizer ignore-type */ $managedCopy, $visited);
Loading history...
1980
1981 41
        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...
1982
    }
1983
1984
    /**
1985
     * @param ClassMetadata $class
1986
     * @param object        $entity
1987
     * @param object        $managedCopy
1988
     *
1989
     * @return void
1990
     *
1991
     * @throws OptimisticLockException
1992
     */
1993 34
    private function ensureVersionMatch(ClassMetadata $class, $entity, $managedCopy)
1994
    {
1995 34
        if (! ($class->isVersioned && $this->isLoaded($managedCopy) && $this->isLoaded($entity))) {
1996 31
            return;
1997
        }
1998
1999 4
        $reflField          = $class->reflFields[$class->versionField];
2000 4
        $managedCopyVersion = $reflField->getValue($managedCopy);
2001 4
        $entityVersion      = $reflField->getValue($entity);
2002
2003
        // Throw exception if versions don't match.
2004 4
        if ($managedCopyVersion == $entityVersion) {
2005 3
            return;
2006
        }
2007
2008 1
        throw OptimisticLockException::lockFailedVersionMismatch($entity, $entityVersion, $managedCopyVersion);
2009
    }
2010
2011
    /**
2012
     * Tests if an entity is loaded - must either be a loaded proxy or not a proxy
2013
     *
2014
     * @param object $entity
2015
     *
2016
     * @return bool
2017
     */
2018 41
    private function isLoaded($entity)
2019
    {
2020 41
        return !($entity instanceof Proxy) || $entity->__isInitialized();
2021
    }
2022
2023
    /**
2024
     * Sets/adds associated managed copies into the previous entity's association field
2025
     *
2026
     * @param object $entity
2027
     * @param array  $association
2028
     * @param object $previousManagedCopy
2029
     * @param object $managedCopy
2030
     *
2031
     * @return void
2032
     */
2033 6
    private function updateAssociationWithMergedEntity($entity, array $association, $previousManagedCopy, $managedCopy)
2034
    {
2035 6
        $assocField = $association['fieldName'];
2036 6
        $prevClass  = $this->em->getClassMetadata(get_class($previousManagedCopy));
2037
2038 6
        if ($association['type'] & ClassMetadata::TO_ONE) {
2039 6
            $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...
2040
2041 6
            return;
2042
        }
2043
2044 1
        $value   = $prevClass->reflFields[$assocField]->getValue($previousManagedCopy);
2045 1
        $value[] = $managedCopy;
2046
2047 1
        if ($association['type'] == ClassMetadata::ONE_TO_MANY) {
2048 1
            $class = $this->em->getClassMetadata(get_class($entity));
2049
2050 1
            $class->reflFields[$association['mappedBy']]->setValue($managedCopy, $previousManagedCopy);
2051
        }
2052 1
    }
2053
2054
    /**
2055
     * Detaches an entity from the persistence management. It's persistence will
2056
     * no longer be managed by Doctrine.
2057
     *
2058
     * @param object $entity The entity to detach.
2059
     *
2060
     * @return void
2061
     */
2062 12
    public function detach($entity)
2063
    {
2064 12
        $visited = [];
2065
2066 12
        $this->doDetach($entity, $visited);
2067 12
    }
2068
2069
    /**
2070
     * Executes a detach operation on the given entity.
2071
     *
2072
     * @param object  $entity
2073
     * @param array   $visited
2074
     * @param boolean $noCascade if true, don't cascade detach operation.
2075
     *
2076
     * @return void
2077
     */
2078 16
    private function doDetach($entity, array &$visited, $noCascade = false)
2079
    {
2080 16
        $oid = spl_object_hash($entity);
2081
2082 16
        if (isset($visited[$oid])) {
2083
            return; // Prevent infinite recursion
2084
        }
2085
2086 16
        $visited[$oid] = $entity; // mark visited
2087
2088 16
        switch ($this->getEntityState($entity, self::STATE_DETACHED)) {
2089 16
            case self::STATE_MANAGED:
2090 14
                if ($this->isInIdentityMap($entity)) {
2091 13
                    $this->removeFromIdentityMap($entity);
2092
                }
2093
2094
                unset(
2095 14
                    $this->entityInsertions[$oid],
2096 14
                    $this->entityUpdates[$oid],
2097 14
                    $this->entityDeletions[$oid],
2098 14
                    $this->entityIdentifiers[$oid],
2099 14
                    $this->entityStates[$oid],
2100 14
                    $this->originalEntityData[$oid]
2101
                );
2102 14
                break;
2103 3
            case self::STATE_NEW:
2104 3
            case self::STATE_DETACHED:
2105 3
                return;
2106
        }
2107
2108 14
        if ( ! $noCascade) {
2109 14
            $this->cascadeDetach($entity, $visited);
2110
        }
2111 14
    }
2112
2113
    /**
2114
     * Refreshes the state of the given entity from the database, overwriting
2115
     * any local, unpersisted changes.
2116
     *
2117
     * @param object $entity The entity to refresh.
2118
     *
2119
     * @return void
2120
     *
2121
     * @throws InvalidArgumentException If the entity is not MANAGED.
2122
     */
2123 17
    public function refresh($entity)
2124
    {
2125 17
        $visited = [];
2126
2127 17
        $this->doRefresh($entity, $visited);
2128 17
    }
2129
2130
    /**
2131
     * Executes a refresh operation on an entity.
2132
     *
2133
     * @param object $entity  The entity to refresh.
2134
     * @param array  $visited The already visited entities during cascades.
2135
     *
2136
     * @return void
2137
     *
2138
     * @throws ORMInvalidArgumentException If the entity is not MANAGED.
2139
     */
2140 17
    private function doRefresh($entity, array &$visited)
2141
    {
2142 17
        $oid = spl_object_hash($entity);
2143
2144 17
        if (isset($visited[$oid])) {
2145
            return; // Prevent infinite recursion
2146
        }
2147
2148 17
        $visited[$oid] = $entity; // mark visited
2149
2150 17
        $class = $this->em->getClassMetadata(get_class($entity));
2151
2152 17
        if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
2153
            throw ORMInvalidArgumentException::entityNotManaged($entity);
2154
        }
2155
2156 17
        $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...
2157 17
            array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
2158 17
            $entity
2159
        );
2160
2161 17
        $this->cascadeRefresh($entity, $visited);
2162 17
    }
2163
2164
    /**
2165
     * Cascades a refresh operation to associated entities.
2166
     *
2167
     * @param object $entity
2168
     * @param array  $visited
2169
     *
2170
     * @return void
2171
     */
2172 17
    private function cascadeRefresh($entity, array &$visited)
2173
    {
2174 17
        $class = $this->em->getClassMetadata(get_class($entity));
2175
2176 17
        $associationMappings = array_filter(
2177 17
            $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...
2178
            function ($assoc) { return $assoc['isCascadeRefresh']; }
2179
        );
2180
2181 17
        foreach ($associationMappings as $assoc) {
2182 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...
2183
2184
            switch (true) {
2185 5
                case ($relatedEntities instanceof PersistentCollection):
2186
                    // Unwrap so that foreach() does not initialize
2187 5
                    $relatedEntities = $relatedEntities->unwrap();
2188
                    // break; is commented intentionally!
2189
2190
                case ($relatedEntities instanceof Collection):
2191
                case (is_array($relatedEntities)):
2192 5
                    foreach ($relatedEntities as $relatedEntity) {
2193
                        $this->doRefresh($relatedEntity, $visited);
2194
                    }
2195 5
                    break;
2196
2197
                case ($relatedEntities !== null):
2198
                    $this->doRefresh($relatedEntities, $visited);
2199
                    break;
2200
2201 5
                default:
2202
                    // Do nothing
2203
            }
2204
        }
2205 17
    }
2206
2207
    /**
2208
     * Cascades a detach operation to associated entities.
2209
     *
2210
     * @param object $entity
2211
     * @param array  $visited
2212
     *
2213
     * @return void
2214
     */
2215 14
    private function cascadeDetach($entity, array &$visited)
2216
    {
2217 14
        $class = $this->em->getClassMetadata(get_class($entity));
2218
2219 14
        $associationMappings = array_filter(
2220 14
            $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...
2221
            function ($assoc) { return $assoc['isCascadeDetach']; }
2222
        );
2223
2224 14
        foreach ($associationMappings as $assoc) {
2225 3
            $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...
2226
2227
            switch (true) {
2228 3
                case ($relatedEntities instanceof PersistentCollection):
2229
                    // Unwrap so that foreach() does not initialize
2230 2
                    $relatedEntities = $relatedEntities->unwrap();
2231
                    // break; is commented intentionally!
2232
2233 1
                case ($relatedEntities instanceof Collection):
2234
                case (is_array($relatedEntities)):
2235 3
                    foreach ($relatedEntities as $relatedEntity) {
2236 1
                        $this->doDetach($relatedEntity, $visited);
2237
                    }
2238 3
                    break;
2239
2240
                case ($relatedEntities !== null):
2241
                    $this->doDetach($relatedEntities, $visited);
2242
                    break;
2243
2244 3
                default:
2245
                    // Do nothing
2246
            }
2247
        }
2248 14
    }
2249
2250
    /**
2251
     * Cascades a merge operation to associated entities.
2252
     *
2253
     * @param object $entity
2254
     * @param object $managedCopy
2255
     * @param array  $visited
2256
     *
2257
     * @return void
2258
     */
2259 41
    private function cascadeMerge($entity, $managedCopy, array &$visited)
2260
    {
2261 41
        $class = $this->em->getClassMetadata(get_class($entity));
2262
2263 41
        $associationMappings = array_filter(
2264 41
            $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...
2265
            function ($assoc) { return $assoc['isCascadeMerge']; }
2266
        );
2267
2268 41
        foreach ($associationMappings as $assoc) {
2269 16
            $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...
2270
2271 16
            if ($relatedEntities instanceof Collection) {
2272 10
                if ($relatedEntities === $class->reflFields[$assoc['fieldName']]->getValue($managedCopy)) {
2273 1
                    continue;
2274
                }
2275
2276 9
                if ($relatedEntities instanceof PersistentCollection) {
2277
                    // Unwrap so that foreach() does not initialize
2278 5
                    $relatedEntities = $relatedEntities->unwrap();
2279
                }
2280
2281 9
                foreach ($relatedEntities as $relatedEntity) {
2282 9
                    $this->doMerge($relatedEntity, $visited, $managedCopy, $assoc);
2283
                }
2284 7
            } else if ($relatedEntities !== null) {
2285 15
                $this->doMerge($relatedEntities, $visited, $managedCopy, $assoc);
2286
            }
2287
        }
2288 41
    }
2289
2290
    /**
2291
     * Cascades the save operation to associated entities.
2292
     *
2293
     * @param object $entity
2294
     * @param array  $visited
2295
     *
2296
     * @return void
2297
     */
2298 1104
    private function cascadePersist($entity, array &$visited)
2299
    {
2300 1104
        $class = $this->em->getClassMetadata(get_class($entity));
2301
2302 1104
        $associationMappings = array_filter(
2303 1104
            $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...
2304
            function ($assoc) { return $assoc['isCascadePersist']; }
2305
        );
2306
2307 1104
        foreach ($associationMappings as $assoc) {
2308 685
            $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...
2309
2310
            switch (true) {
2311 685
                case ($relatedEntities instanceof PersistentCollection):
2312
                    // Unwrap so that foreach() does not initialize
2313 21
                    $relatedEntities = $relatedEntities->unwrap();
2314
                    // break; is commented intentionally!
2315
2316 685
                case ($relatedEntities instanceof Collection):
2317 621
                case (is_array($relatedEntities)):
2318 576
                    if (($assoc['type'] & ClassMetadata::TO_MANY) <= 0) {
2319 3
                        throw ORMInvalidArgumentException::invalidAssociation(
2320 3
                            $this->em->getClassMetadata($assoc['targetEntity']),
2321 3
                            $assoc,
2322 3
                            $relatedEntities
2323
                        );
2324
                    }
2325
2326 573
                    foreach ($relatedEntities as $relatedEntity) {
2327 293
                        $this->doPersist($relatedEntity, $visited);
2328
                    }
2329
2330 573
                    break;
2331
2332 610
                case ($relatedEntities !== null):
2333 254
                    if (! $relatedEntities instanceof $assoc['targetEntity']) {
2334 4
                        throw ORMInvalidArgumentException::invalidAssociation(
2335 4
                            $this->em->getClassMetadata($assoc['targetEntity']),
2336 4
                            $assoc,
2337 4
                            $relatedEntities
2338
                        );
2339
                    }
2340
2341 250
                    $this->doPersist($relatedEntities, $visited);
2342 250
                    break;
2343
2344 679
                default:
2345
                    // Do nothing
2346
            }
2347
        }
2348 1097
    }
2349
2350
    /**
2351
     * Cascades the delete operation to associated entities.
2352
     *
2353
     * @param object $entity
2354
     * @param array  $visited
2355
     *
2356
     * @return void
2357
     */
2358 66
    private function cascadeRemove($entity, array &$visited)
2359
    {
2360 66
        $class = $this->em->getClassMetadata(get_class($entity));
2361
2362 66
        $associationMappings = array_filter(
2363 66
            $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...
2364
            function ($assoc) { return $assoc['isCascadeRemove']; }
2365
        );
2366
2367 66
        $entitiesToCascade = [];
2368
2369 66
        foreach ($associationMappings as $assoc) {
2370 26
            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...
2371 6
                $entity->__load();
2372
            }
2373
2374 26
            $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...
2375
2376
            switch (true) {
2377 26
                case ($relatedEntities instanceof Collection):
2378 19
                case (is_array($relatedEntities)):
2379
                    // If its a PersistentCollection initialization is intended! No unwrap!
2380 20
                    foreach ($relatedEntities as $relatedEntity) {
2381 10
                        $entitiesToCascade[] = $relatedEntity;
2382
                    }
2383 20
                    break;
2384
2385 19
                case ($relatedEntities !== null):
2386 7
                    $entitiesToCascade[] = $relatedEntities;
2387 7
                    break;
2388
2389 26
                default:
2390
                    // Do nothing
2391
            }
2392
        }
2393
2394 66
        foreach ($entitiesToCascade as $relatedEntity) {
2395 16
            $this->doRemove($relatedEntity, $visited);
2396
        }
2397 66
    }
2398
2399
    /**
2400
     * Acquire a lock on the given entity.
2401
     *
2402
     * @param object $entity
2403
     * @param int    $lockMode
2404
     * @param int    $lockVersion
2405
     *
2406
     * @return void
2407
     *
2408
     * @throws ORMInvalidArgumentException
2409
     * @throws TransactionRequiredException
2410
     * @throws OptimisticLockException
2411
     */
2412 10
    public function lock($entity, $lockMode, $lockVersion = null)
2413
    {
2414 10
        if ($entity === null) {
2415 1
            throw new \InvalidArgumentException("No entity passed to UnitOfWork#lock().");
2416
        }
2417
2418 9
        if ($this->getEntityState($entity, self::STATE_DETACHED) != self::STATE_MANAGED) {
2419 1
            throw ORMInvalidArgumentException::entityNotManaged($entity);
2420
        }
2421
2422 8
        $class = $this->em->getClassMetadata(get_class($entity));
2423
2424
        switch (true) {
2425 8
            case LockMode::OPTIMISTIC === $lockMode:
2426 6
                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...
2427 1
                    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...
2428
                }
2429
2430 5
                if ($lockVersion === null) {
2431 1
                    return;
2432
                }
2433
2434 4
                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...
2435 1
                    $entity->__load();
2436
                }
2437
2438 4
                $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...
2439
2440 4
                if ($entityVersion != $lockVersion) {
2441 2
                    throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion);
2442
                }
2443
2444 2
                break;
2445
2446 2
            case LockMode::NONE === $lockMode:
2447 2
            case LockMode::PESSIMISTIC_READ === $lockMode:
2448 1
            case LockMode::PESSIMISTIC_WRITE === $lockMode:
2449 2
                if (!$this->em->getConnection()->isTransactionActive()) {
2450 2
                    throw TransactionRequiredException::transactionRequired();
2451
                }
2452
2453
                $oid = spl_object_hash($entity);
2454
2455
                $this->getEntityPersister($class->name)->lock(
2456
                    array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
2457
                    $lockMode
2458
                );
2459
                break;
2460
2461
            default:
2462
                // Do nothing
2463
        }
2464 2
    }
2465
2466
    /**
2467
     * Gets the CommitOrderCalculator used by the UnitOfWork to order commits.
2468
     *
2469
     * @return \Doctrine\ORM\Internal\CommitOrderCalculator
2470
     */
2471 1079
    public function getCommitOrderCalculator()
2472
    {
2473 1079
        return new Internal\CommitOrderCalculator();
2474
    }
2475
2476
    /**
2477
     * Clears the UnitOfWork.
2478
     *
2479
     * @param string|null $entityName if given, only entities of this type will get detached.
2480
     *
2481
     * @return void
2482
     *
2483
     * @throws ORMInvalidArgumentException if an invalid entity name is given
2484
     */
2485 1305
    public function clear($entityName = null)
2486
    {
2487 1305
        if ($entityName === null) {
2488 1303
            $this->identityMap =
2489 1303
            $this->entityIdentifiers =
2490 1303
            $this->originalEntityData =
2491 1303
            $this->entityChangeSets =
2492 1303
            $this->entityStates =
2493 1303
            $this->scheduledForSynchronization =
2494 1303
            $this->entityInsertions =
2495 1303
            $this->entityUpdates =
2496 1303
            $this->entityDeletions =
2497 1303
            $this->nonCascadedNewDetectedEntities =
2498 1303
            $this->collectionDeletions =
2499 1303
            $this->collectionUpdates =
2500 1303
            $this->extraUpdates =
2501 1303
            $this->readOnlyObjects =
2502 1303
            $this->visitedCollections =
2503 1303
            $this->orphanRemovals = [];
2504
        } else {
2505 4
            $this->clearIdentityMapForEntityName($entityName);
2506 4
            $this->clearEntityInsertionsForEntityName($entityName);
2507
        }
2508
2509 1305
        if ($this->evm->hasListeners(Events::onClear)) {
2510 9
            $this->evm->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->em, $entityName));
2511
        }
2512 1305
    }
2513
2514
    /**
2515
     * INTERNAL:
2516
     * Schedules an orphaned entity for removal. The remove() operation will be
2517
     * invoked on that entity at the beginning of the next commit of this
2518
     * UnitOfWork.
2519
     *
2520
     * @ignore
2521
     *
2522
     * @param object $entity
2523
     *
2524
     * @return void
2525
     */
2526 17
    public function scheduleOrphanRemoval($entity)
2527
    {
2528 17
        $this->orphanRemovals[spl_object_hash($entity)] = $entity;
2529 17
    }
2530
2531
    /**
2532
     * INTERNAL:
2533
     * Cancels a previously scheduled orphan removal.
2534
     *
2535
     * @ignore
2536
     *
2537
     * @param object $entity
2538
     *
2539
     * @return void
2540
     */
2541 117
    public function cancelOrphanRemoval($entity)
2542
    {
2543 117
        unset($this->orphanRemovals[spl_object_hash($entity)]);
2544 117
    }
2545
2546
    /**
2547
     * INTERNAL:
2548
     * Schedules a complete collection for removal when this UnitOfWork commits.
2549
     *
2550
     * @param PersistentCollection $coll
2551
     *
2552
     * @return void
2553
     */
2554 14
    public function scheduleCollectionDeletion(PersistentCollection $coll)
2555
    {
2556 14
        $coid = spl_object_hash($coll);
2557
2558
        // TODO: if $coll is already scheduled for recreation ... what to do?
2559
        // Just remove $coll from the scheduled recreations?
2560 14
        unset($this->collectionUpdates[$coid]);
2561
2562 14
        $this->collectionDeletions[$coid] = $coll;
2563 14
    }
2564
2565
    /**
2566
     * @param PersistentCollection $coll
2567
     *
2568
     * @return bool
2569
     */
2570
    public function isCollectionScheduledForDeletion(PersistentCollection $coll)
2571
    {
2572
        return isset($this->collectionDeletions[spl_object_hash($coll)]);
2573
    }
2574
2575
    /**
2576
     * @param ClassMetadata $class
2577
     *
2578
     * @return \Doctrine\Common\Persistence\ObjectManagerAware|object
2579
     */
2580 714
    private function newInstance($class)
2581
    {
2582 714
        $entity = $class->newInstance();
2583
2584 714
        if ($entity instanceof \Doctrine\Common\Persistence\ObjectManagerAware) {
2585 4
            $entity->injectObjectManager($this->em, $class);
2586
        }
2587
2588 714
        return $entity;
2589
    }
2590
2591
    /**
2592
     * INTERNAL:
2593
     * Creates an entity. Used for reconstitution of persistent entities.
2594
     *
2595
     * Internal note: Highly performance-sensitive method.
2596
     *
2597
     * @ignore
2598
     *
2599
     * @param string $className The name of the entity class.
2600
     * @param array  $data      The data for the entity.
2601
     * @param array  $hints     Any hints to account for during reconstitution/lookup of the entity.
2602
     *
2603
     * @return object The managed entity instance.
2604
     *
2605
     * @todo Rename: getOrCreateEntity
2606
     */
2607 856
    public function createEntity($className, array $data, &$hints = [])
2608
    {
2609 856
        $class = $this->em->getClassMetadata($className);
2610
2611 856
        $id = $this->identifierFlattener->flattenIdentifier($class, $data);
2612 856
        $idHash = implode(' ', $id);
2613
2614 856
        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...
2615 325
            $entity = $this->identityMap[$class->rootEntityName][$idHash];
2616 325
            $oid = spl_object_hash($entity);
2617
2618
            if (
2619 325
                isset($hints[Query::HINT_REFRESH])
2620 325
                && isset($hints[Query::HINT_REFRESH_ENTITY])
2621 325
                && ($unmanagedProxy = $hints[Query::HINT_REFRESH_ENTITY]) !== $entity
2622 325
                && $unmanagedProxy instanceof Proxy
2623 325
                && $this->isIdentifierEquals($unmanagedProxy, $entity)
2624
            ) {
2625
                // DDC-1238 - we have a managed instance, but it isn't the provided one.
2626
                // Therefore we clear its identifier. Also, we must re-fetch metadata since the
2627
                // refreshed object may be anything
2628
2629 2
                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...
2630 2
                    $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...
2631
                }
2632
2633 2
                return $unmanagedProxy;
2634
            }
2635
2636 323
            if ($entity instanceof Proxy && ! $entity->__isInitialized()) {
2637 23
                $entity->__setInitialized(true);
2638
2639 23
                if ($entity instanceof NotifyPropertyChanged) {
2640 23
                    $entity->addPropertyChangedListener($this);
2641
                }
2642
            } else {
2643 302
                if ( ! isset($hints[Query::HINT_REFRESH])
2644 302
                    || (isset($hints[Query::HINT_REFRESH_ENTITY]) && $hints[Query::HINT_REFRESH_ENTITY] !== $entity)) {
2645 231
                    return $entity;
2646
                }
2647
            }
2648
2649
            // inject ObjectManager upon refresh.
2650 115
            if ($entity instanceof ObjectManagerAware) {
2651 3
                $entity->injectObjectManager($this->em, $class);
2652
            }
2653
2654 115
            $this->originalEntityData[$oid] = $data;
2655
        } else {
2656 709
            $entity = $this->newInstance($class);
2657 709
            $oid    = spl_object_hash($entity);
2658
2659 709
            $this->entityIdentifiers[$oid]  = $id;
2660 709
            $this->entityStates[$oid]       = self::STATE_MANAGED;
2661 709
            $this->originalEntityData[$oid] = $data;
2662
2663 709
            $this->identityMap[$class->rootEntityName][$idHash] = $entity;
2664
2665 709
            if ($entity instanceof NotifyPropertyChanged) {
2666 2
                $entity->addPropertyChangedListener($this);
2667
            }
2668
        }
2669
2670 747
        foreach ($data as $field => $value) {
2671 747
            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...
2672 747
                $class->reflFields[$field]->setValue($entity, $value);
2673
            }
2674
        }
2675
2676
        // Loading the entity right here, if its in the eager loading map get rid of it there.
2677 747
        unset($this->eagerLoadingEntities[$class->rootEntityName][$idHash]);
2678
2679 747
        if (isset($this->eagerLoadingEntities[$class->rootEntityName]) && ! $this->eagerLoadingEntities[$class->rootEntityName]) {
2680
            unset($this->eagerLoadingEntities[$class->rootEntityName]);
2681
        }
2682
2683
        // Properly initialize any unfetched associations, if partial objects are not allowed.
2684 747
        if (isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
2685 34
            return $entity;
2686
        }
2687
2688 713
        foreach ($class->associationMappings as $field => $assoc) {
2689
            // Check if the association is not among the fetch-joined associations already.
2690 611
            if (isset($hints['fetchAlias']) && isset($hints['fetched'][$hints['fetchAlias']][$field])) {
2691 260
                continue;
2692
            }
2693
2694 587
            $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
2695
2696
            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...
2697 587
                case ($assoc['type'] & ClassMetadata::TO_ONE):
2698 507
                    if ( ! $assoc['isOwningSide']) {
2699
2700
                        // use the given entity association
2701 67
                        if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) {
2702
2703 3
                            $this->originalEntityData[$oid][$field] = $data[$field];
2704
2705 3
                            $class->reflFields[$field]->setValue($entity, $data[$field]);
2706 3
                            $targetClass->reflFields[$assoc['mappedBy']]->setValue($data[$field], $entity);
2707
2708 3
                            continue 2;
2709
                        }
2710
2711
                        // Inverse side of x-to-one can never be lazy
2712 64
                        $class->reflFields[$field]->setValue($entity, $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity));
2713
2714 64
                        continue 2;
2715
                    }
2716
2717
                    // use the entity association
2718 507
                    if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) {
2719 38
                        $class->reflFields[$field]->setValue($entity, $data[$field]);
2720 38
                        $this->originalEntityData[$oid][$field] = $data[$field];
2721
2722 38
                        break;
2723
                    }
2724
2725 500
                    $associatedId = [];
2726
2727
                    // TODO: Is this even computed right in all cases of composite keys?
2728 500
                    foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
2729 500
                        $joinColumnValue = $data[$srcColumn] ?? null;
2730
2731 500
                        if ($joinColumnValue !== null) {
2732 300
                            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...
2733 12
                                $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue;
2734
                            } else {
2735 300
                                $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...
2736
                            }
2737 294
                        } elseif ($targetClass->containsForeignIdentifier
2738 294
                            && in_array($targetClass->getFieldForColumn($targetColumn), $targetClass->identifier, true)
2739
                        ) {
2740
                            // the missing key is part of target's entity primary key
2741 7
                            $associatedId = [];
2742 500
                            break;
2743
                        }
2744
                    }
2745
2746 500
                    if ( ! $associatedId) {
2747
                        // Foreign key is NULL
2748 294
                        $class->reflFields[$field]->setValue($entity, null);
2749 294
                        $this->originalEntityData[$oid][$field] = null;
2750
2751 294
                        break;
2752
                    }
2753
2754 300
                    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...
2755 297
                        $hints['fetchMode'][$class->name][$field] = $assoc['fetch'];
2756
                    }
2757
2758
                    // Foreign key is set
2759
                    // Check identity map first
2760
                    // FIXME: Can break easily with composite keys if join column values are in
2761
                    //        wrong order. The correct order is the one in ClassMetadata#identifier.
2762 300
                    $relatedIdHash = implode(' ', $associatedId);
2763
2764
                    switch (true) {
2765 300
                        case (isset($this->identityMap[$targetClass->rootEntityName][$relatedIdHash])):
2766 174
                            $newValue = $this->identityMap[$targetClass->rootEntityName][$relatedIdHash];
2767
2768
                            // If this is an uninitialized proxy, we are deferring eager loads,
2769
                            // this association is marked as eager fetch, and its an uninitialized proxy (wtf!)
2770
                            // then we can append this entity for eager loading!
2771 174
                            if ($hints['fetchMode'][$class->name][$field] == ClassMetadata::FETCH_EAGER &&
2772 174
                                isset($hints[self::HINT_DEFEREAGERLOAD]) &&
2773 174
                                !$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...
2774 174
                                $newValue instanceof Proxy &&
2775 174
                                $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...
2776
2777
                                $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
2778
                            }
2779
2780 174
                            break;
2781
2782 204
                        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...
2783
                            // If it might be a subtype, it can not be lazy. There isn't even
2784
                            // a way to solve this with deferred eager loading, which means putting
2785
                            // an entity with subclasses at a *-to-one location is really bad! (performance-wise)
2786 32
                            $newValue = $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity, $associatedId);
2787 32
                            break;
2788
2789
                        default:
2790
                            switch (true) {
2791
                                // We are negating the condition here. Other cases will assume it is valid!
2792 174
                                case ($hints['fetchMode'][$class->name][$field] !== ClassMetadata::FETCH_EAGER):
2793 167
                                    $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
2794 167
                                    break;
2795
2796
                                // Deferred eager load only works for single identifier classes
2797 7
                                case (isset($hints[self::HINT_DEFEREAGERLOAD]) && ! $targetClass->isIdentifierComposite):
2798
                                    // TODO: Is there a faster approach?
2799 7
                                    $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
2800
2801 7
                                    $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
2802 7
                                    break;
2803
2804
                                default:
2805
                                    // TODO: This is very imperformant, ignore it?
2806
                                    $newValue = $this->em->find($assoc['targetEntity'], $associatedId);
2807
                                    break;
2808
                            }
2809
2810
                            // PERF: Inlined & optimized code from UnitOfWork#registerManaged()
2811 174
                            $newValueOid = spl_object_hash($newValue);
2812 174
                            $this->entityIdentifiers[$newValueOid] = $associatedId;
2813 174
                            $this->identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue;
2814
2815
                            if (
2816 174
                                $newValue instanceof NotifyPropertyChanged &&
2817 174
                                ( ! $newValue instanceof Proxy || $newValue->__isInitialized())
2818
                            ) {
2819
                                $newValue->addPropertyChangedListener($this);
2820
                            }
2821 174
                            $this->entityStates[$newValueOid] = self::STATE_MANAGED;
2822
                            // make sure that when an proxy is then finally loaded, $this->originalEntityData is set also!
2823 174
                            break;
2824
                    }
2825
2826 300
                    $this->originalEntityData[$oid][$field] = $newValue;
2827 300
                    $class->reflFields[$field]->setValue($entity, $newValue);
2828
2829 300
                    if ($assoc['inversedBy'] && $assoc['type'] & ClassMetadata::ONE_TO_ONE) {
2830 59
                        $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...
2831 59
                        $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($newValue, $entity);
2832
                    }
2833
2834 300
                    break;
2835
2836
                default:
2837
                    // Ignore if its a cached collection
2838 497
                    if (isset($hints[Query::HINT_CACHE_ENABLED]) && $class->getFieldValue($entity, $field) instanceof PersistentCollection) {
2839
                        break;
2840
                    }
2841
2842
                    // use the given collection
2843 497
                    if (isset($data[$field]) && $data[$field] instanceof PersistentCollection) {
2844
2845 3
                        $data[$field]->setOwner($entity, $assoc);
2846
2847 3
                        $class->reflFields[$field]->setValue($entity, $data[$field]);
2848 3
                        $this->originalEntityData[$oid][$field] = $data[$field];
2849
2850 3
                        break;
2851
                    }
2852
2853
                    // Inject collection
2854 497
                    $pColl = new PersistentCollection($this->em, $targetClass, new ArrayCollection);
2855 497
                    $pColl->setOwner($entity, $assoc);
2856 497
                    $pColl->setInitialized(false);
2857
2858 497
                    $reflField = $class->reflFields[$field];
2859 497
                    $reflField->setValue($entity, $pColl);
2860
2861 497
                    if ($assoc['fetch'] == ClassMetadata::FETCH_EAGER) {
2862 4
                        $this->loadCollection($pColl);
2863 4
                        $pColl->takeSnapshot();
2864
                    }
2865
2866 497
                    $this->originalEntityData[$oid][$field] = $pColl;
2867 587
                    break;
2868
            }
2869
        }
2870
2871
        // defer invoking of postLoad event to hydration complete step
2872 713
        $this->hydrationCompleteHandler->deferPostLoadInvoking($class, $entity);
2873
2874 713
        return $entity;
2875
    }
2876
2877
    /**
2878
     * @return void
2879
     */
2880 924
    public function triggerEagerLoads()
2881
    {
2882 924
        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...
2883 924
            return;
2884
        }
2885
2886
        // avoid infinite recursion
2887 7
        $eagerLoadingEntities       = $this->eagerLoadingEntities;
2888 7
        $this->eagerLoadingEntities = [];
2889
2890 7
        foreach ($eagerLoadingEntities as $entityName => $ids) {
2891 7
            if ( ! $ids) {
2892
                continue;
2893
            }
2894
2895 7
            $class = $this->em->getClassMetadata($entityName);
2896
2897 7
            $this->getEntityPersister($entityName)->loadAll(
2898 7
                array_combine($class->identifier, [array_values($ids)])
0 ignored issues
show
Bug introduced by
Accessing identifier on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
2899
            );
2900
        }
2901 7
    }
2902
2903
    /**
2904
     * Initializes (loads) an uninitialized persistent collection of an entity.
2905
     *
2906
     * @param \Doctrine\ORM\PersistentCollection $collection The collection to initialize.
2907
     *
2908
     * @return void
2909
     *
2910
     * @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733.
2911
     */
2912 148
    public function loadCollection(PersistentCollection $collection)
2913
    {
2914 148
        $assoc     = $collection->getMapping();
2915 148
        $persister = $this->getEntityPersister($assoc['targetEntity']);
2916
2917 148
        switch ($assoc['type']) {
2918 148
            case ClassMetadata::ONE_TO_MANY:
2919 78
                $persister->loadOneToManyCollection($assoc, $collection->getOwner(), $collection);
2920 78
                break;
2921
2922 84
            case ClassMetadata::MANY_TO_MANY:
2923 84
                $persister->loadManyToManyCollection($assoc, $collection->getOwner(), $collection);
2924 84
                break;
2925
        }
2926
2927 148
        $collection->setInitialized(true);
2928 148
    }
2929
2930
    /**
2931
     * Gets the identity map of the UnitOfWork.
2932
     *
2933
     * @return array
2934
     */
2935 2
    public function getIdentityMap()
2936
    {
2937 2
        return $this->identityMap;
2938
    }
2939
2940
    /**
2941
     * Gets the original data of an entity. The original data is the data that was
2942
     * present at the time the entity was reconstituted from the database.
2943
     *
2944
     * @param object $entity
2945
     *
2946
     * @return array
2947
     */
2948 122
    public function getOriginalEntityData($entity)
2949
    {
2950 122
        $oid = spl_object_hash($entity);
2951
2952 122
        return isset($this->originalEntityData[$oid])
2953 118
            ? $this->originalEntityData[$oid]
2954 122
            : [];
2955
    }
2956
2957
    /**
2958
     * @ignore
2959
     *
2960
     * @param object $entity
2961
     * @param array  $data
2962
     *
2963
     * @return void
2964
     */
2965
    public function setOriginalEntityData($entity, array $data)
2966
    {
2967
        $this->originalEntityData[spl_object_hash($entity)] = $data;
2968
    }
2969
2970
    /**
2971
     * INTERNAL:
2972
     * Sets a property value of the original data array of an entity.
2973
     *
2974
     * @ignore
2975
     *
2976
     * @param string $oid
2977
     * @param string $property
2978
     * @param mixed  $value
2979
     *
2980
     * @return void
2981
     */
2982 314
    public function setOriginalEntityProperty($oid, $property, $value)
2983
    {
2984 314
        $this->originalEntityData[$oid][$property] = $value;
2985 314
    }
2986
2987
    /**
2988
     * Gets the identifier of an entity.
2989
     * The returned value is always an array of identifier values. If the entity
2990
     * has a composite identifier then the identifier values are in the same
2991
     * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
2992
     *
2993
     * @param object $entity
2994
     *
2995
     * @return array The identifier values.
2996
     */
2997 876
    public function getEntityIdentifier($entity)
2998
    {
2999 876
        return $this->entityIdentifiers[spl_object_hash($entity)];
3000
    }
3001
3002
    /**
3003
     * Processes an entity instance to extract their identifier values.
3004
     *
3005
     * @param object $entity The entity instance.
3006
     *
3007
     * @return mixed A scalar value.
3008
     *
3009
     * @throws \Doctrine\ORM\ORMInvalidArgumentException
3010
     */
3011 136
    public function getSingleIdentifierValue($entity)
3012
    {
3013 136
        $class = $this->em->getClassMetadata(get_class($entity));
3014
3015 134
        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...
3016
            throw ORMInvalidArgumentException::invalidCompositeIdentifier();
3017
        }
3018
3019 134
        $values = $this->isInIdentityMap($entity)
3020 120
            ? $this->getEntityIdentifier($entity)
3021 134
            : $class->getIdentifierValues($entity);
3022
3023 134
        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...
3024
    }
3025
3026
    /**
3027
     * Tries to find an entity with the given identifier in the identity map of
3028
     * this UnitOfWork.
3029
     *
3030
     * @param mixed  $id            The entity identifier to look for.
3031
     * @param string $rootClassName The name of the root class of the mapped entity hierarchy.
3032
     *
3033
     * @return object|bool Returns the entity with the specified identifier if it exists in
3034
     *                     this UnitOfWork, FALSE otherwise.
3035
     */
3036 558
    public function tryGetById($id, $rootClassName)
3037
    {
3038 558
        $idHash = implode(' ', (array) $id);
3039
3040 558
        return isset($this->identityMap[$rootClassName][$idHash])
3041 89
            ? $this->identityMap[$rootClassName][$idHash]
3042 558
            : false;
3043
    }
3044
3045
    /**
3046
     * Schedules an entity for dirty-checking at commit-time.
3047
     *
3048
     * @param object $entity The entity to schedule for dirty-checking.
3049
     *
3050
     * @return void
3051
     *
3052
     * @todo Rename: scheduleForSynchronization
3053
     */
3054 6
    public function scheduleForDirtyCheck($entity)
3055
    {
3056 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...
3057
3058 6
        $this->scheduledForSynchronization[$rootClassName][spl_object_hash($entity)] = $entity;
3059 6
    }
3060
3061
    /**
3062
     * Checks whether the UnitOfWork has any pending insertions.
3063
     *
3064
     * @return boolean TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
3065
     */
3066
    public function hasPendingInsertions()
3067
    {
3068
        return ! empty($this->entityInsertions);
3069
    }
3070
3071
    /**
3072
     * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
3073
     * number of entities in the identity map.
3074
     *
3075
     * @return integer
3076
     */
3077 1
    public function size()
3078
    {
3079 1
        $countArray = array_map('count', $this->identityMap);
3080
3081 1
        return array_sum($countArray);
3082
    }
3083
3084
    /**
3085
     * Gets the EntityPersister for an Entity.
3086
     *
3087
     * @param string $entityName The name of the Entity.
3088
     *
3089
     * @return \Doctrine\ORM\Persisters\Entity\EntityPersister
3090
     */
3091 1139
    public function getEntityPersister($entityName)
3092
    {
3093 1139
        if (isset($this->persisters[$entityName])) {
3094 898
            return $this->persisters[$entityName];
3095
        }
3096
3097 1139
        $class = $this->em->getClassMetadata($entityName);
3098
3099
        switch (true) {
3100 1139
            case ($class->isInheritanceTypeNone()):
3101 1090
                $persister = new BasicEntityPersister($this->em, $class);
3102 1090
                break;
3103
3104 394
            case ($class->isInheritanceTypeSingleTable()):
3105 226
                $persister = new SingleTablePersister($this->em, $class);
3106 226
                break;
3107
3108 361
            case ($class->isInheritanceTypeJoined()):
3109 361
                $persister = new JoinedSubclassPersister($this->em, $class);
3110 361
                break;
3111
3112
            default:
3113
                throw new \RuntimeException('No persister found for entity.');
3114
        }
3115
3116 1139
        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...
3117 126
            $persister = $this->em->getConfiguration()
3118 126
                ->getSecondLevelCacheConfiguration()
3119 126
                ->getCacheFactory()
3120 126
                ->buildCachedEntityPersister($this->em, $persister, $class);
3121
        }
3122
3123 1139
        $this->persisters[$entityName] = $persister;
3124
3125 1139
        return $this->persisters[$entityName];
3126
    }
3127
3128
    /**
3129
     * Gets a collection persister for a collection-valued association.
3130
     *
3131
     * @param array $association
3132
     *
3133
     * @return \Doctrine\ORM\Persisters\Collection\CollectionPersister
3134
     */
3135 582
    public function getCollectionPersister(array $association)
3136
    {
3137 582
        $role = isset($association['cache'])
3138 78
            ? $association['sourceEntity'] . '::' . $association['fieldName']
3139 582
            : $association['type'];
3140
3141 582
        if (isset($this->collectionPersisters[$role])) {
3142 457
            return $this->collectionPersisters[$role];
3143
        }
3144
3145 582
        $persister = ClassMetadata::ONE_TO_MANY === $association['type']
3146 411
            ? new OneToManyPersister($this->em)
3147 582
            : new ManyToManyPersister($this->em);
3148
3149 582
        if ($this->hasCache && isset($association['cache'])) {
3150 77
            $persister = $this->em->getConfiguration()
3151 77
                ->getSecondLevelCacheConfiguration()
3152 77
                ->getCacheFactory()
3153 77
                ->buildCachedCollectionPersister($this->em, $persister, $association);
3154
        }
3155
3156 582
        $this->collectionPersisters[$role] = $persister;
3157
3158 582
        return $this->collectionPersisters[$role];
3159
    }
3160
3161
    /**
3162
     * INTERNAL:
3163
     * Registers an entity as managed.
3164
     *
3165
     * @param object $entity The entity.
3166
     * @param array  $id     The identifier values.
3167
     * @param array  $data   The original entity data.
3168
     *
3169
     * @return void
3170
     */
3171 210
    public function registerManaged($entity, array $id, array $data)
3172
    {
3173 210
        $oid = spl_object_hash($entity);
3174
3175 210
        $this->entityIdentifiers[$oid]  = $id;
3176 210
        $this->entityStates[$oid]       = self::STATE_MANAGED;
3177 210
        $this->originalEntityData[$oid] = $data;
3178
3179 210
        $this->addToIdentityMap($entity);
3180
3181 204
        if ($entity instanceof NotifyPropertyChanged && ( ! $entity instanceof Proxy || $entity->__isInitialized())) {
3182 2
            $entity->addPropertyChangedListener($this);
3183
        }
3184 204
    }
3185
3186
    /**
3187
     * INTERNAL:
3188
     * Clears the property changeset of the entity with the given OID.
3189
     *
3190
     * @param string $oid The entity's OID.
3191
     *
3192
     * @return void
3193
     */
3194 16
    public function clearEntityChangeSet($oid)
3195
    {
3196 16
        unset($this->entityChangeSets[$oid]);
3197 16
    }
3198
3199
    /* PropertyChangedListener implementation */
3200
3201
    /**
3202
     * Notifies this UnitOfWork of a property change in an entity.
3203
     *
3204
     * @param object $entity       The entity that owns the property.
3205
     * @param string $propertyName The name of the property that changed.
3206
     * @param mixed  $oldValue     The old value of the property.
3207
     * @param mixed  $newValue     The new value of the property.
3208
     *
3209
     * @return void
3210
     */
3211 4
    public function propertyChanged($entity, $propertyName, $oldValue, $newValue)
3212
    {
3213 4
        $oid   = spl_object_hash($entity);
3214 4
        $class = $this->em->getClassMetadata(get_class($entity));
3215
3216 4
        $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...
3217
3218 4
        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...
3219 1
            return; // ignore non-persistent fields
3220
        }
3221
3222
        // Update changeset and mark entity for synchronization
3223 4
        $this->entityChangeSets[$oid][$propertyName] = [$oldValue, $newValue];
3224
3225 4
        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...
3226 4
            $this->scheduleForDirtyCheck($entity);
3227
        }
3228 4
    }
3229
3230
    /**
3231
     * Gets the currently scheduled entity insertions in this UnitOfWork.
3232
     *
3233
     * @return array
3234
     */
3235 2
    public function getScheduledEntityInsertions()
3236
    {
3237 2
        return $this->entityInsertions;
3238
    }
3239
3240
    /**
3241
     * Gets the currently scheduled entity updates in this UnitOfWork.
3242
     *
3243
     * @return array
3244
     */
3245 3
    public function getScheduledEntityUpdates()
3246
    {
3247 3
        return $this->entityUpdates;
3248
    }
3249
3250
    /**
3251
     * Gets the currently scheduled entity deletions in this UnitOfWork.
3252
     *
3253
     * @return array
3254
     */
3255 1
    public function getScheduledEntityDeletions()
3256
    {
3257 1
        return $this->entityDeletions;
3258
    }
3259
3260
    /**
3261
     * Gets the currently scheduled complete collection deletions
3262
     *
3263
     * @return array
3264
     */
3265 1
    public function getScheduledCollectionDeletions()
3266
    {
3267 1
        return $this->collectionDeletions;
3268
    }
3269
3270
    /**
3271
     * Gets the currently scheduled collection inserts, updates and deletes.
3272
     *
3273
     * @return array
3274
     */
3275
    public function getScheduledCollectionUpdates()
3276
    {
3277
        return $this->collectionUpdates;
3278
    }
3279
3280
    /**
3281
     * Helper method to initialize a lazy loading proxy or persistent collection.
3282
     *
3283
     * @param object $obj
3284
     *
3285
     * @return void
3286
     */
3287 2
    public function initializeObject($obj)
3288
    {
3289 2
        if ($obj instanceof Proxy) {
3290 1
            $obj->__load();
3291
3292 1
            return;
3293
        }
3294
3295 1
        if ($obj instanceof PersistentCollection) {
3296 1
            $obj->initialize();
3297
        }
3298 1
    }
3299
3300
    /**
3301
     * Helper method to show an object as string.
3302
     *
3303
     * @param object $obj
3304
     *
3305
     * @return string
3306
     */
3307 1
    private static function objToStr($obj)
3308
    {
3309 1
        return method_exists($obj, '__toString') ? (string) $obj : get_class($obj).'@'.spl_object_hash($obj);
3310
    }
3311
3312
    /**
3313
     * Marks an entity as read-only so that it will not be considered for updates during UnitOfWork#commit().
3314
     *
3315
     * This operation cannot be undone as some parts of the UnitOfWork now keep gathering information
3316
     * on this object that might be necessary to perform a correct update.
3317
     *
3318
     * @param object $object
3319
     *
3320
     * @return void
3321
     *
3322
     * @throws ORMInvalidArgumentException
3323
     */
3324 6
    public function markReadOnly($object)
3325
    {
3326 6
        if ( ! is_object($object) || ! $this->isInIdentityMap($object)) {
3327 1
            throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
3328
        }
3329
3330 5
        $this->readOnlyObjects[spl_object_hash($object)] = true;
3331 5
    }
3332
3333
    /**
3334
     * Is this entity read only?
3335
     *
3336
     * @param object $object
3337
     *
3338
     * @return bool
3339
     *
3340
     * @throws ORMInvalidArgumentException
3341
     */
3342 3
    public function isReadOnly($object)
3343
    {
3344 3
        if ( ! is_object($object)) {
3345
            throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
3346
        }
3347
3348 3
        return isset($this->readOnlyObjects[spl_object_hash($object)]);
3349
    }
3350
3351
    /**
3352
     * Perform whatever processing is encapsulated here after completion of the transaction.
3353
     */
3354
    private function afterTransactionComplete()
3355
    {
3356 1074
        $this->performCallbackOnCachedPersister(function (CachedPersister $persister) {
3357 95
            $persister->afterTransactionComplete();
3358 1074
        });
3359 1074
    }
3360
3361
    /**
3362
     * Perform whatever processing is encapsulated here after completion of the rolled-back.
3363
     */
3364
    private function afterTransactionRolledBack()
3365
    {
3366 11
        $this->performCallbackOnCachedPersister(function (CachedPersister $persister) {
3367 3
            $persister->afterTransactionRolledBack();
3368 11
        });
3369 11
    }
3370
3371
    /**
3372
     * Performs an action after the transaction.
3373
     *
3374
     * @param callable $callback
3375
     */
3376 1079
    private function performCallbackOnCachedPersister(callable $callback)
3377
    {
3378 1079
        if ( ! $this->hasCache) {
3379 984
            return;
3380
        }
3381
3382 95
        foreach (array_merge($this->persisters, $this->collectionPersisters) as $persister) {
3383 95
            if ($persister instanceof CachedPersister) {
3384 95
                $callback($persister);
3385
            }
3386
        }
3387 95
    }
3388
3389 1083
    private function dispatchOnFlushEvent()
3390
    {
3391 1083
        if ($this->evm->hasListeners(Events::onFlush)) {
3392 4
            $this->evm->dispatchEvent(Events::onFlush, new OnFlushEventArgs($this->em));
3393
        }
3394 1083
    }
3395
3396 1078
    private function dispatchPostFlushEvent()
3397
    {
3398 1078
        if ($this->evm->hasListeners(Events::postFlush)) {
3399 5
            $this->evm->dispatchEvent(Events::postFlush, new PostFlushEventArgs($this->em));
3400
        }
3401 1077
    }
3402
3403
    /**
3404
     * Verifies if two given entities actually are the same based on identifier comparison
3405
     *
3406
     * @param object $entity1
3407
     * @param object $entity2
3408
     *
3409
     * @return bool
3410
     */
3411 14
    private function isIdentifierEquals($entity1, $entity2)
3412
    {
3413 14
        if ($entity1 === $entity2) {
3414
            return true;
3415
        }
3416
3417 14
        $class = $this->em->getClassMetadata(get_class($entity1));
3418
3419 14
        if ($class !== $this->em->getClassMetadata(get_class($entity2))) {
3420 11
            return false;
3421
        }
3422
3423 3
        $oid1 = spl_object_hash($entity1);
3424 3
        $oid2 = spl_object_hash($entity2);
3425
3426 3
        $id1 = isset($this->entityIdentifiers[$oid1])
3427 3
            ? $this->entityIdentifiers[$oid1]
3428 3
            : $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($entity1));
3429 3
        $id2 = isset($this->entityIdentifiers[$oid2])
3430 3
            ? $this->entityIdentifiers[$oid2]
3431 3
            : $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($entity2));
3432
3433 3
        return $id1 === $id2 || implode(' ', $id1) === implode(' ', $id2);
3434
    }
3435
3436
    /**
3437
     * @throws ORMInvalidArgumentException
3438
     */
3439 1081
    private function assertThatThereAreNoUnintentionallyNonPersistedAssociations() : void
3440
    {
3441 1081
        $entitiesNeedingCascadePersist = \array_diff_key($this->nonCascadedNewDetectedEntities, $this->entityInsertions);
3442
3443 1081
        $this->nonCascadedNewDetectedEntities = [];
3444
3445 1081
        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...
3446 5
            throw ORMInvalidArgumentException::newEntitiesFoundThroughRelationships(
3447 5
                \array_values($entitiesNeedingCascadePersist)
3448
            );
3449
        }
3450 1079
    }
3451
3452
    /**
3453
     * @param object $entity
3454
     * @param object $managedCopy
3455
     *
3456
     * @throws ORMException
3457
     * @throws OptimisticLockException
3458
     * @throws TransactionRequiredException
3459
     */
3460 40
    private function mergeEntityStateIntoManagedCopy($entity, $managedCopy)
3461
    {
3462 40
        if (! $this->isLoaded($entity)) {
3463 7
            return;
3464
        }
3465
3466 33
        if (! $this->isLoaded($managedCopy)) {
3467 4
            $managedCopy->__load();
3468
        }
3469
3470 33
        $class = $this->em->getClassMetadata(get_class($entity));
3471
3472 33
        foreach ($this->reflectionPropertiesGetter->getProperties($class->name) as $prop) {
3473 33
            $name = $prop->name;
3474
3475 33
            $prop->setAccessible(true);
3476
3477 33
            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...
3478 33
                if ( ! $class->isIdentifier($name)) {
3479 33
                    $prop->setValue($managedCopy, $prop->getValue($entity));
3480
                }
3481
            } else {
3482 29
                $assoc2 = $class->associationMappings[$name];
3483
3484 29
                if ($assoc2['type'] & ClassMetadata::TO_ONE) {
3485 25
                    $other = $prop->getValue($entity);
3486 25
                    if ($other === null) {
3487 12
                        $prop->setValue($managedCopy, null);
3488
                    } else {
3489 16
                        if ($other instanceof Proxy && !$other->__isInitialized()) {
3490
                            // do not merge fields marked lazy that have not been fetched.
3491 4
                            continue;
3492
                        }
3493
3494 12
                        if ( ! $assoc2['isCascadeMerge']) {
3495 6
                            if ($this->getEntityState($other) === self::STATE_DETACHED) {
3496 3
                                $targetClass = $this->em->getClassMetadata($assoc2['targetEntity']);
3497 3
                                $relatedId   = $targetClass->getIdentifierValues($other);
3498
3499 3
                                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...
3500 2
                                    $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...
3501
                                } else {
3502 1
                                    $other = $this->em->getProxyFactory()->getProxy(
3503 1
                                        $assoc2['targetEntity'],
3504 1
                                        $relatedId
3505
                                    );
3506 1
                                    $this->registerManaged($other, $relatedId, []);
3507
                                }
3508
                            }
3509
3510 21
                            $prop->setValue($managedCopy, $other);
3511
                        }
3512
                    }
3513
                } else {
3514 17
                    $mergeCol = $prop->getValue($entity);
3515
3516 17
                    if ($mergeCol instanceof PersistentCollection && ! $mergeCol->isInitialized()) {
3517
                        // do not merge fields marked lazy that have not been fetched.
3518
                        // keep the lazy persistent collection of the managed copy.
3519 5
                        continue;
3520
                    }
3521
3522 14
                    $managedCol = $prop->getValue($managedCopy);
3523
3524 14
                    if ( ! $managedCol) {
3525 4
                        $managedCol = new PersistentCollection(
3526 4
                            $this->em,
3527 4
                            $this->em->getClassMetadata($assoc2['targetEntity']),
3528 4
                            new ArrayCollection
3529
                        );
3530 4
                        $managedCol->setOwner($managedCopy, $assoc2);
3531 4
                        $prop->setValue($managedCopy, $managedCol);
3532
                    }
3533
3534 14
                    if ($assoc2['isCascadeMerge']) {
3535 9
                        $managedCol->initialize();
3536
3537
                        // clear and set dirty a managed collection if its not also the same collection to merge from.
3538 9
                        if ( ! $managedCol->isEmpty() && $managedCol !== $mergeCol) {
3539 1
                            $managedCol->unwrap()->clear();
3540 1
                            $managedCol->setDirty(true);
3541
3542 1
                            if ($assoc2['isOwningSide']
3543 1
                                && $assoc2['type'] == ClassMetadata::MANY_TO_MANY
3544 1
                                && $class->isChangeTrackingNotify()
3545
                            ) {
3546
                                $this->scheduleForDirtyCheck($managedCopy);
3547
                            }
3548
                        }
3549
                    }
3550
                }
3551
            }
3552
3553 33
            if ($class->isChangeTrackingNotify()) {
3554
                // Just treat all properties as changed, there is no other choice.
3555 33
                $this->propertyChanged($managedCopy, $name, null, $prop->getValue($managedCopy));
3556
            }
3557
        }
3558 33
    }
3559
3560
    /**
3561
     * This method called by hydrators, and indicates that hydrator totally completed current hydration cycle.
3562
     * Unit of work able to fire deferred events, related to loading events here.
3563
     *
3564
     * @internal should be called internally from object hydrators
3565
     */
3566 939
    public function hydrationComplete()
3567
    {
3568 939
        $this->hydrationCompleteHandler->hydrationComplete();
3569 939
    }
3570
3571
    /**
3572
     * @param string $entityName
3573
     */
3574 4
    private function clearIdentityMapForEntityName($entityName)
3575
    {
3576 4
        if (! isset($this->identityMap[$entityName])) {
3577
            return;
3578
        }
3579
3580 4
        $visited = [];
3581
3582 4
        foreach ($this->identityMap[$entityName] as $entity) {
3583 4
            $this->doDetach($entity, $visited, false);
3584
        }
3585 4
    }
3586
3587
    /**
3588
     * @param string $entityName
3589
     */
3590 4
    private function clearEntityInsertionsForEntityName($entityName)
3591
    {
3592 4
        foreach ($this->entityInsertions as $hash => $entity) {
3593
            // note: performance optimization - `instanceof` is much faster than a function call
3594 1
            if ($entity instanceof $entityName && get_class($entity) === $entityName) {
3595 1
                unset($this->entityInsertions[$hash]);
3596
            }
3597
        }
3598 4
    }
3599
3600
    /**
3601
     * @param ClassMetadata $class
3602
     * @param mixed         $identifierValue
3603
     *
3604
     * @return mixed the identifier after type conversion
3605
     *
3606
     * @throws \Doctrine\ORM\Mapping\MappingException if the entity has more than a single identifier
3607
     */
3608 976
    private function convertSingleFieldIdentifierToPHPValue(ClassMetadata $class, $identifierValue)
3609
    {
3610 976
        return $this->em->getConnection()->convertToPHPValue(
3611 976
            $identifierValue,
3612 976
            $class->getTypeOfField($class->getSingleIdentifierFieldName())
3613
        );
3614
    }
3615
}
3616