Completed
Pull Request — master (#14)
by Pavel
04:11
created

UnitOfWork::cascadeRemove()   D

Complexity

Conditions 9
Paths 26

Size

Total Lines 34
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
dl 0
loc 34
c 0
b 0
f 0
ccs 0
cts 30
cp 0
rs 4.909
cc 9
eloc 23
nc 26
nop 2
crap 90
1
<?php
2
3
namespace Bankiru\Api\Doctrine;
4
5
use Bankiru\Api\Doctrine\Cache\ApiEntityCache;
6
use Bankiru\Api\Doctrine\Cache\EntityCacheAwareInterface;
7
use Bankiru\Api\Doctrine\Cache\LoggingCache;
8
use Bankiru\Api\Doctrine\Cache\VoidEntityCache;
9
use Bankiru\Api\Doctrine\Exception\MappingException;
10
use Bankiru\Api\Doctrine\Hydration\EntityHydrator;
11
use Bankiru\Api\Doctrine\Mapping\ApiMetadata;
12
use Bankiru\Api\Doctrine\Mapping\EntityMetadata;
13
use Bankiru\Api\Doctrine\Persister\ApiPersister;
14
use Bankiru\Api\Doctrine\Persister\CollectionPersister;
15
use Bankiru\Api\Doctrine\Persister\EntityPersister;
16
use Bankiru\Api\Doctrine\Proxy\ApiCollection;
17
use Bankiru\Api\Doctrine\Rpc\CrudsApiInterface;
18
use Bankiru\Api\Doctrine\Utility\IdentifierFlattener;
19
use Bankiru\Api\Doctrine\Utility\ReflectionPropertiesGetter;
20
use Doctrine\Common\Collections\ArrayCollection;
21
use Doctrine\Common\Collections\Collection;
22
use Doctrine\Common\NotifyPropertyChanged;
23
use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService;
24
use Doctrine\Common\Persistence\ObjectManagerAware;
25
use Doctrine\Common\PropertyChangedListener;
26
use Doctrine\Common\Proxy\Proxy;
27
28
class UnitOfWork implements PropertyChangedListener
29
{
30
    /**
31
     * An entity is in MANAGED state when its persistence is managed by an EntityManager.
32
     */
33
    const STATE_MANAGED = 1;
34
    /**
35
     * An entity is new if it has just been instantiated (i.e. using the "new" operator)
36
     * and is not (yet) managed by an EntityManager.
37
     */
38
    const STATE_NEW = 2;
39
    /**
40
     * A detached entity is an instance with persistent state and identity that is not
41
     * (or no longer) associated with an EntityManager (and a UnitOfWork).
42
     */
43
    const STATE_DETACHED = 3;
44
    /**
45
     * A removed entity instance is an instance with a persistent identity,
46
     * associated with an EntityManager, whose persistent state will be deleted
47
     * on commit.
48
     */
49
    const STATE_REMOVED = 4;
50
51
    /**
52
     * The (cached) states of any known entities.
53
     * Keys are object ids (spl_object_hash).
54
     *
55
     * @var array
56
     */
57
    private $entityStates = [];
58
59
    /** @var  EntityManager */
60
    private $manager;
61
    /** @var EntityPersister[] */
62
    private $persisters = [];
63
    /** @var CollectionPersister[] */
64
    private $collectionPersisters = [];
65
    /** @var  array */
66
    private $entityIdentifiers = [];
67
    /** @var  object[][] */
68
    private $identityMap = [];
69
    /** @var IdentifierFlattener */
70
    private $identifierFlattener;
71
    /** @var  array */
72
    private $originalEntityData = [];
73
    /** @var  array */
74
    private $entityDeletions = [];
75
    /** @var  array */
76
    private $entityChangeSets = [];
77
    /** @var  array */
78
    private $entityInsertions = [];
79
    /** @var  array */
80
    private $entityUpdates = [];
81
    /** @var  array */
82
    private $readOnlyObjects = [];
83
    /** @var  array */
84
    private $scheduledForSynchronization = [];
85
    /** @var  array */
86
    private $orphanRemovals = [];
87
    /** @var  ApiCollection[] */
88
    private $collectionDeletions = [];
89
    /** @var  array */
90
    private $extraUpdates = [];
91
    /** @var  ApiCollection[] */
92
    private $collectionUpdates = [];
93
    /** @var  ApiCollection[] */
94
    private $visitedCollections = [];
95
    /** @var ReflectionPropertiesGetter */
96
    private $reflectionPropertiesGetter;
97
98
    /**
99
     * UnitOfWork constructor.
100
     *
101
     * @param EntityManager $manager
102
     */
103 20
    public function __construct(EntityManager $manager)
104
    {
105 20
        $this->manager                    = $manager;
106 20
        $this->identifierFlattener        = new IdentifierFlattener($this->manager);
107 20
        $this->reflectionPropertiesGetter = new ReflectionPropertiesGetter(new RuntimeReflectionService());
108 20
    }
109
110
    /**
111
     * @param $className
112
     *
113
     * @return EntityPersister
114
     */
115 19
    public function getEntityPersister($className)
116
    {
117 19
        if (!array_key_exists($className, $this->persisters)) {
118
            /** @var ApiMetadata $classMetadata */
119 19
            $classMetadata = $this->manager->getClassMetadata($className);
120
121 19
            $api = $this->createApi($classMetadata);
122
123 19
            if ($api instanceof EntityCacheAwareInterface) {
124 19
                $api->setEntityCache($this->createEntityCache($classMetadata));
125 19
            }
126
127 19
            $this->persisters[$className] = new ApiPersister($this->manager, $api);
128 19
        }
129
130 19
        return $this->persisters[$className];
131
    }
132
133
    /**
134
     * Checks whether an entity is registered in the identity map of this UnitOfWork.
135
     *
136
     * @param object $entity
137
     *
138
     * @return boolean
139
     */
140
    public function isInIdentityMap($entity)
141
    {
142
        $oid = spl_object_hash($entity);
143
144
        if (!isset($this->entityIdentifiers[$oid])) {
145
            return false;
146
        }
147
148
        /** @var EntityMetadata $classMetadata */
149
        $classMetadata = $this->manager->getClassMetadata(get_class($entity));
150
        $idHash        = implode(' ', $this->entityIdentifiers[$oid]);
151
152
        if ($idHash === '') {
153
            return false;
154
        }
155
156
        return isset($this->identityMap[$classMetadata->rootEntityName][$idHash]);
157
    }
158
159
    /**
160
     * Gets the identifier of an entity.
161
     * The returned value is always an array of identifier values. If the entity
162
     * has a composite identifier then the identifier values are in the same
163
     * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
164
     *
165
     * @param object $entity
166
     *
167
     * @return array The identifier values.
168
     */
169 1
    public function getEntityIdentifier($entity)
170
    {
171 1
        return $this->entityIdentifiers[spl_object_hash($entity)];
172
    }
173
174
    /**
175
     * @param             $className
176
     * @param \stdClass   $data
177
     *
178
     * @return ObjectManagerAware|object
179
     * @throws MappingException
180
     */
181 13
    public function getOrCreateEntity($className, \stdClass $data)
182
    {
183
        /** @var EntityMetadata $class */
184 13
        $class    = $this->manager->getClassMetadata($className);
185 13
        $hydrator = new EntityHydrator($this->manager, $class);
186
187 13
        $tmpEntity = $hydrator->hydarate($data);
188
189 13
        $id     = $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($tmpEntity));
190 13
        $idHash = implode(' ', $id);
191
192 13
        $overrideLocalValues = false;
193 13
        if (isset($this->identityMap[$class->rootEntityName][$idHash])) {
194 2
            $entity = $this->identityMap[$class->rootEntityName][$idHash];
195 2
            $oid    = spl_object_hash($entity);
196
197 2
            if ($entity instanceof Proxy && !$entity->__isInitialized()) {
198 2
                $entity->__setInitialized(true);
199
200 2
                $overrideLocalValues            = true;
201 2
                $this->originalEntityData[$oid] = $data;
202
203 2
                if ($entity instanceof NotifyPropertyChanged) {
204
                    $entity->addPropertyChangedListener($this);
205
                }
206 2
            }
207 2
        } else {
208 12
            $entity                                             = $this->newInstance($class);
209 12
            $oid                                                = spl_object_hash($entity);
210 12
            $this->entityIdentifiers[$oid]                      = $id;
211 12
            $this->entityStates[$oid]                           = self::STATE_MANAGED;
212 12
            $this->originalEntityData[$oid]                     = $data;
213 12
            $this->identityMap[$class->rootEntityName][$idHash] = $entity;
214 12
            if ($entity instanceof NotifyPropertyChanged) {
215
                $entity->addPropertyChangedListener($this);
216
            }
217 12
            $overrideLocalValues = true;
218
        }
219
220 13
        if (!$overrideLocalValues) {
221
            return $entity;
222
        }
223
224 13
        $entity = $hydrator->hydarate($data, $entity);
225
226 13
        return $entity;
227
    }
228
229
    /**
230
     * INTERNAL:
231
     * Registers an entity as managed.
232
     *
233
     * @param object         $entity The entity.
234
     * @param array          $id     The identifier values.
235
     * @param \stdClass|null $data   The original entity data.
236
     *
237
     * @return void
238
     */
239 4
    public function registerManaged($entity, array $id, \stdClass $data = null)
240
    {
241 4
        $oid = spl_object_hash($entity);
242
243 4
        $this->entityIdentifiers[$oid]  = $id;
244 4
        $this->entityStates[$oid]       = self::STATE_MANAGED;
245 4
        $this->originalEntityData[$oid] = $data;
246
247 4
        $this->addToIdentityMap($entity);
248
249 4
        if ($entity instanceof NotifyPropertyChanged && (!$entity instanceof Proxy || $entity->__isInitialized())) {
250
            $entity->addPropertyChangedListener($this);
251
        }
252 4
    }
253
254
    /**
255
     * INTERNAL:
256
     * Registers an entity in the identity map.
257
     * Note that entities in a hierarchy are registered with the class name of
258
     * the root entity.
259
     *
260
     * @ignore
261
     *
262
     * @param object $entity The entity to register.
263
     *
264
     * @return boolean TRUE if the registration was successful, FALSE if the identity of
265
     *                 the entity in question is already managed.
266
     *
267
     */
268 9
    public function addToIdentityMap($entity)
269
    {
270
        /** @var EntityMetadata $classMetadata */
271 9
        $classMetadata = $this->manager->getClassMetadata(get_class($entity));
272 9
        $idHash        = implode(' ', $this->entityIdentifiers[spl_object_hash($entity)]);
273
274 9
        if ($idHash === '') {
275
            throw new \InvalidArgumentException('Entitty does not have valid identifiers to be stored at identity map');
276
        }
277
278 9
        $className = $classMetadata->rootEntityName;
279
280 9
        if (isset($this->identityMap[$className][$idHash])) {
281
            return false;
282
        }
283
284 9
        $this->identityMap[$className][$idHash] = $entity;
285
286 9
        return true;
287
    }
288
289
    /**
290
     * Gets the identity map of the UnitOfWork.
291
     *
292
     * @return array
293
     */
294
    public function getIdentityMap()
295
    {
296
        return $this->identityMap;
297
    }
298
299
    /**
300
     * Gets the original data of an entity. The original data is the data that was
301
     * present at the time the entity was reconstituted from the database.
302
     *
303
     * @param object $entity
304
     *
305
     * @return array
306
     */
307
    public function getOriginalEntityData($entity)
308
    {
309
        $oid = spl_object_hash($entity);
310
311
        if (isset($this->originalEntityData[$oid])) {
312
            return $this->originalEntityData[$oid];
313
        }
314
315
        return [];
316
    }
317
318
    /**
319
     * INTERNAL:
320
     * Checks whether an identifier hash exists in the identity map.
321
     *
322
     * @ignore
323
     *
324
     * @param string $idHash
325
     * @param string $rootClassName
326
     *
327
     * @return boolean
328
     */
329
    public function containsIdHash($idHash, $rootClassName)
330
    {
331
        return isset($this->identityMap[$rootClassName][$idHash]);
332
    }
333
334
    /**
335
     * INTERNAL:
336
     * Gets an entity in the identity map by its identifier hash.
337
     *
338
     * @ignore
339
     *
340
     * @param string $idHash
341
     * @param string $rootClassName
342
     *
343
     * @return object
344
     */
345
    public function getByIdHash($idHash, $rootClassName)
346
    {
347
        return $this->identityMap[$rootClassName][$idHash];
348
    }
349
350
    /**
351
     * INTERNAL:
352
     * Tries to get an entity by its identifier hash. If no entity is found for
353
     * the given hash, FALSE is returned.
354
     *
355
     * @ignore
356
     *
357
     * @param mixed  $idHash (must be possible to cast it to string)
358
     * @param string $rootClassName
359
     *
360
     * @return object|bool The found entity or FALSE.
361
     */
362
    public function tryGetByIdHash($idHash, $rootClassName)
363
    {
364
        $stringIdHash = (string)$idHash;
365
366
        if (isset($this->identityMap[$rootClassName][$stringIdHash])) {
367
            return $this->identityMap[$rootClassName][$stringIdHash];
368
        }
369
370
        return false;
371
    }
372
373
    /**
374
     * Gets the state of an entity with regard to the current unit of work.
375
     *
376
     * @param object   $entity
377
     * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
378
     *                         This parameter can be set to improve performance of entity state detection
379
     *                         by potentially avoiding a database lookup if the distinction between NEW and DETACHED
380
     *                         is either known or does not matter for the caller of the method.
381
     *
382
     * @return int The entity state.
383
     */
384 5
    public function getEntityState($entity, $assume = null)
385
    {
386 5
        $oid = spl_object_hash($entity);
387 5
        if (isset($this->entityStates[$oid])) {
388 2
            return $this->entityStates[$oid];
389
        }
390 5
        if ($assume !== null) {
391 5
            return $assume;
392
        }
393
        // State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
394
        // Note that you can not remember the NEW or DETACHED state in _entityStates since
395
        // the UoW does not hold references to such objects and the object hash can be reused.
396
        // More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
397
        $class = $this->manager->getClassMetadata(get_class($entity));
398
        $id    = $class->getIdentifierValues($entity);
399
        if (!$id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
400
            return self::STATE_NEW;
401
        }
402
403
        return self::STATE_DETACHED;
404
    }
405
406
    /**
407
     * Tries to find an entity with the given identifier in the identity map of
408
     * this UnitOfWork.
409
     *
410
     * @param mixed  $id            The entity identifier to look for.
411
     * @param string $rootClassName The name of the root class of the mapped entity hierarchy.
412
     *
413
     * @return object|bool Returns the entity with the specified identifier if it exists in
414
     *                     this UnitOfWork, FALSE otherwise.
415
     */
416 12
    public function tryGetById($id, $rootClassName)
417
    {
418
        /** @var EntityMetadata $metadata */
419 12
        $metadata = $this->manager->getClassMetadata($rootClassName);
420 12
        $idHash   = implode(' ', (array)$this->identifierFlattener->flattenIdentifier($metadata, $id));
421
422 12
        if (isset($this->identityMap[$rootClassName][$idHash])) {
423 5
            return $this->identityMap[$rootClassName][$idHash];
424
        }
425
426 12
        return false;
427
    }
428
429
    /**
430
     * Notifies this UnitOfWork of a property change in an entity.
431
     *
432
     * @param object $entity       The entity that owns the property.
433
     * @param string $propertyName The name of the property that changed.
434
     * @param mixed  $oldValue     The old value of the property.
435
     * @param mixed  $newValue     The new value of the property.
436
     *
437
     * @return void
438
     */
439
    public function propertyChanged($entity, $propertyName, $oldValue, $newValue)
440
    {
441
        $oid          = spl_object_hash($entity);
442
        $class        = $this->manager->getClassMetadata(get_class($entity));
443
        $isAssocField = $class->hasAssociation($propertyName);
444
        if (!$isAssocField && !$class->hasField($propertyName)) {
445
            return; // ignore non-persistent fields
446
        }
447
        // Update changeset and mark entity for synchronization
448
        $this->entityChangeSets[$oid][$propertyName] = [$oldValue, $newValue];
449
        if (!isset($this->scheduledForSynchronization[$class->getRootEntityName()][$oid])) {
450
            $this->scheduleForDirtyCheck($entity);
451
        }
452
    }
453
454
    /**
455
     * Persists an entity as part of the current unit of work.
456
     *
457
     * @param object $entity The entity to persist.
458
     *
459
     * @return void
460
     */
461 5
    public function persist($entity)
462
    {
463 5
        $visited = [];
464 5
        $this->doPersist($entity, $visited);
465 5
    }
466
467
    /**
468
     * @param ApiMetadata $class
469
     * @param             $entity
470
     *
471
     * @throws \InvalidArgumentException
472
     * @throws \RuntimeException
473
     */
474 1
    public function recomputeSingleEntityChangeSet(ApiMetadata $class, $entity)
475
    {
476 1
        $oid = spl_object_hash($entity);
477 1
        if (!isset($this->entityStates[$oid]) || $this->entityStates[$oid] != self::STATE_MANAGED) {
478
            throw new \InvalidArgumentException('Entity is not managed');
479
        }
480
481 1
        $actualData = [];
482 1
        foreach ($class->getReflectionProperties() as $name => $refProp) {
483 1
            if (!$class->isIdentifier($name) && !$class->isCollectionValuedAssociation($name)) {
484 1
                $actualData[$name] = $refProp->getValue($entity);
485 1
            }
486 1
        }
487 1
        if (!isset($this->originalEntityData[$oid])) {
488
            throw new \RuntimeException(
489
                'Cannot call recomputeSingleEntityChangeSet before computeChangeSet on an entity.'
490
            );
491
        }
492 1
        $originalData = $this->originalEntityData[$oid];
493 1
        $changeSet    = [];
494 1
        foreach ($actualData as $propName => $actualValue) {
495 1
            $orgValue = isset($originalData[$propName]) ? $originalData[$propName] : null;
496 1
            if ($orgValue !== $actualValue) {
497
                $changeSet[$propName] = [$orgValue, $actualValue];
498
            }
499 1
        }
500 1
        if ($changeSet) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $changeSet 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...
501
            if (isset($this->entityChangeSets[$oid])) {
502
                $this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
503
            } else {
504
                if (!isset($this->entityInsertions[$oid])) {
505
                    $this->entityChangeSets[$oid] = $changeSet;
506
                    $this->entityUpdates[$oid]    = $entity;
507
                }
508
            }
509
            $this->originalEntityData[$oid] = $actualData;
510
        }
511 1
    }
512
513
    /**
514
     * Schedules an entity for insertion into the database.
515
     * If the entity already has an identifier, it will be added to the identity map.
516
     *
517
     * @param object $entity The entity to schedule for insertion.
518
     *
519
     * @return void
520
     *
521
     * @throws \InvalidArgumentException
522
     */
523 5
    public function scheduleForInsert($entity)
524
    {
525 5
        $oid = spl_object_hash($entity);
526 5
        if (isset($this->entityUpdates[$oid])) {
527
            throw new \InvalidArgumentException('Dirty entity cannot be scheduled for insertion');
528
        }
529 5
        if (isset($this->entityDeletions[$oid])) {
530
            throw new \InvalidArgumentException('Removed entity scheduled for insertion');
531
        }
532 5
        if (isset($this->originalEntityData[$oid]) && !isset($this->entityInsertions[$oid])) {
533
            throw new \InvalidArgumentException('Managed entity scheduled for insertion');
534
        }
535 5
        if (isset($this->entityInsertions[$oid])) {
536
            throw new \InvalidArgumentException('Entity scheduled for insertion twice');
537
        }
538 5
        $this->entityInsertions[$oid] = $entity;
539 5
        if (isset($this->entityIdentifiers[$oid])) {
540
            $this->addToIdentityMap($entity);
541
        }
542 5
        if ($entity instanceof NotifyPropertyChanged) {
543
            $entity->addPropertyChangedListener($this);
544
        }
545 5
    }
546
547
    /**
548
     * Checks whether an entity is scheduled for insertion.
549
     *
550
     * @param object $entity
551
     *
552
     * @return boolean
553
     */
554 1
    public function isScheduledForInsert($entity)
555
    {
556 1
        return isset($this->entityInsertions[spl_object_hash($entity)]);
557
    }
558
559
    /**
560
     * Schedules an entity for being updated.
561
     *
562
     * @param object $entity The entity to schedule for being updated.
563
     *
564
     * @return void
565
     *
566
     * @throws \InvalidArgumentException
567
     */
568
    public function scheduleForUpdate($entity)
569
    {
570
        $oid = spl_object_hash($entity);
571
        if (!isset($this->entityIdentifiers[$oid])) {
572
            throw new \InvalidArgumentException('Entity has no identity');
573
        }
574
        if (isset($this->entityDeletions[$oid])) {
575
            throw new \InvalidArgumentException('Entity is removed');
576
        }
577
        if (!isset($this->entityUpdates[$oid]) && !isset($this->entityInsertions[$oid])) {
578
            $this->entityUpdates[$oid] = $entity;
579
        }
580
    }
581
582
    /**
583
     * Checks whether an entity is registered as dirty in the unit of work.
584
     * Note: Is not very useful currently as dirty entities are only registered
585
     * at commit time.
586
     *
587
     * @param object $entity
588
     *
589
     * @return boolean
590
     */
591
    public function isScheduledForUpdate($entity)
592
    {
593
        return isset($this->entityUpdates[spl_object_hash($entity)]);
594
    }
595
596
    /**
597
     * Checks whether an entity is registered to be checked in the unit of work.
598
     *
599
     * @param object $entity
600
     *
601
     * @return boolean
602
     */
603
    public function isScheduledForDirtyCheck($entity)
604
    {
605
        $rootEntityName = $this->manager->getClassMetadata(get_class($entity))->getRootEntityName();
606
607
        return isset($this->scheduledForSynchronization[$rootEntityName][spl_object_hash($entity)]);
608
    }
609
610
    /**
611
     * INTERNAL:
612
     * Schedules an entity for deletion.
613
     *
614
     * @param object $entity
615
     *
616
     * @return void
617
     */
618
    public function scheduleForDelete($entity)
619
    {
620
        $oid = spl_object_hash($entity);
621
        if (isset($this->entityInsertions[$oid])) {
622
            if ($this->isInIdentityMap($entity)) {
623
                $this->removeFromIdentityMap($entity);
624
            }
625
            unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
626
627
            return; // entity has not been persisted yet, so nothing more to do.
628
        }
629
        if (!$this->isInIdentityMap($entity)) {
630
            return;
631
        }
632
        $this->removeFromIdentityMap($entity);
633
        unset($this->entityUpdates[$oid]);
634
        if (!isset($this->entityDeletions[$oid])) {
635
            $this->entityDeletions[$oid] = $entity;
636
            $this->entityStates[$oid]    = self::STATE_REMOVED;
637
        }
638
    }
639
640
    /**
641
     * Checks whether an entity is registered as removed/deleted with the unit
642
     * of work.
643
     *
644
     * @param object $entity
645
     *
646
     * @return boolean
647
     */
648
    public function isScheduledForDelete($entity)
649
    {
650
        return isset($this->entityDeletions[spl_object_hash($entity)]);
651
    }
652
653
    /**
654
     * Checks whether an entity is scheduled for insertion, update or deletion.
655
     *
656
     * @param object $entity
657
     *
658
     * @return boolean
659
     */
660
    public function isEntityScheduled($entity)
661
    {
662
        $oid = spl_object_hash($entity);
663
664
        return isset($this->entityInsertions[$oid])
665
               || isset($this->entityUpdates[$oid])
666
               || isset($this->entityDeletions[$oid]);
667
    }
668
669
    /**
670
     * INTERNAL:
671
     * Removes an entity from the identity map. This effectively detaches the
672
     * entity from the persistence management of Doctrine.
673
     *
674
     * @ignore
675
     *
676
     * @param object $entity
677
     *
678
     * @return boolean
679
     *
680
     * @throws \InvalidArgumentException
681
     */
682
    public function removeFromIdentityMap($entity)
683
    {
684
        $oid           = spl_object_hash($entity);
685
        $classMetadata = $this->manager->getClassMetadata(get_class($entity));
686
        $idHash        = implode(' ', $this->entityIdentifiers[$oid]);
687
        if ($idHash === '') {
688
            throw new \InvalidArgumentException('Entity has no identity');
689
        }
690
        $className = $classMetadata->getRootEntityName();
691
        if (isset($this->identityMap[$className][$idHash])) {
692
            unset($this->identityMap[$className][$idHash]);
693
            unset($this->readOnlyObjects[$oid]);
694
695
            //$this->entityStates[$oid] = self::STATE_DETACHED;
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
696
            return true;
697
        }
698
699
        return false;
700
    }
701
702
    /**
703
     * Commits the UnitOfWork, executing all operations that have been postponed
704
     * up to this point. The state of all managed entities will be synchronized with
705
     * the database.
706
     *
707
     * The operations are executed in the following order:
708
     *
709
     * 1) All entity insertions
710
     * 2) All entity updates
711
     * 3) All collection deletions
712
     * 4) All collection updates
713
     * 5) All entity deletions
714
     *
715
     * @param null|object|array $entity
716
     *
717
     * @return void
718
     *
719
     * @throws \Exception
720
     */
721 5
    public function commit($entity = null)
722
    {
723
        // Compute changes done since last commit.
724 5
        if ($entity === null) {
725 5
            $this->computeChangeSets();
726 5
        } elseif (is_object($entity)) {
727
            $this->computeSingleEntityChangeSet($entity);
728
        } elseif (is_array($entity)) {
729
            foreach ((array)$entity as $object) {
730
                $this->computeSingleEntityChangeSet($object);
731
            }
732
        }
733 5
        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...
734 1
              $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...
735 1
              $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...
736 1
              $this->collectionUpdates ||
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->collectionUpdates of type Bankiru\Api\Doctrine\Proxy\ApiCollection[] 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...
737 1
              $this->collectionDeletions ||
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->collectionDeletions of type Bankiru\Api\Doctrine\Proxy\ApiCollection[] 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...
738 1
              $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...
739 5
        ) {
740 1
            return; // Nothing to do.
741
        }
742 5
        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...
743
            foreach ($this->orphanRemovals as $orphan) {
744
                $this->remove($orphan);
745
            }
746
        }
747
        // Now we need a commit order to maintain referential integrity
748 5
        $commitOrder = $this->getCommitOrder();
749
750
        // Collection deletions (deletions of complete collections)
751
        // foreach ($this->collectionDeletions as $collectionToDelete) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
752
        //       //fixme: collection mutations
753
        //       $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
754
        // }
755 5
        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...
756 5
            foreach ($commitOrder as $class) {
757 5
                $this->executeInserts($class);
758 5
            }
759 5
        }
760 5
        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...
761 1
            foreach ($commitOrder as $class) {
762 1
                $this->executeUpdates($class);
763 1
            }
764 1
        }
765
        // Extra updates that were requested by persisters.
766 5
        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...
767
            $this->executeExtraUpdates();
768
        }
769
        // Collection updates (deleteRows, updateRows, insertRows)
770 5
        foreach ($this->collectionUpdates as $collectionToUpdate) {
0 ignored issues
show
Unused Code introduced by
This foreach statement is empty and can be removed.

This check looks for foreach loops that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

Consider removing the loop.

Loading history...
771
            //fixme: decide what to do with collection mutation if API does not support this
772
            //$this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
773 5
        }
774
        // Entity deletions come last and need to be in reverse commit order
775 5
        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...
776
            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...
777
                $this->executeDeletions($commitOrder[$i]);
778
            }
779
        }
780
781
        // Take new snapshots from visited collections
782 5
        foreach ($this->visitedCollections as $coll) {
783 2
            $coll->takeSnapshot();
784 5
        }
785
786
        // Clear up
787 5
        $this->entityInsertions =
788 5
        $this->entityUpdates =
789 5
        $this->entityDeletions =
790 5
        $this->extraUpdates =
791 5
        $this->entityChangeSets =
792 5
        $this->collectionUpdates =
793 5
        $this->collectionDeletions =
794 5
        $this->visitedCollections =
795 5
        $this->scheduledForSynchronization =
796 5
        $this->orphanRemovals = [];
797 5
    }
798
799
    /**
800
     * Gets the changeset for an entity.
801
     *
802
     * @param object $entity
803
     *
804
     * @return array
805
     */
806 1
    public function & getEntityChangeSet($entity)
807
    {
808 1
        $oid  = spl_object_hash($entity);
809 1
        $data = [];
810 1
        if (!isset($this->entityChangeSets[$oid])) {
811
            return $data;
812
        }
813
814 1
        return $this->entityChangeSets[$oid];
815
    }
816
817
    /**
818
     * Computes the changes that happened to a single entity.
819
     *
820
     * Modifies/populates the following properties:
821
     *
822
     * {@link _originalEntityData}
823
     * If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
824
     * then it was not fetched from the database and therefore we have no original
825
     * entity data yet. All of the current entity data is stored as the original entity data.
826
     *
827
     * {@link _entityChangeSets}
828
     * The changes detected on all properties of the entity are stored there.
829
     * A change is a tuple array where the first entry is the old value and the second
830
     * entry is the new value of the property. Changesets are used by persisters
831
     * to INSERT/UPDATE the persistent entity state.
832
     *
833
     * {@link _entityUpdates}
834
     * If the entity is already fully MANAGED (has been fetched from the database before)
835
     * and any changes to its properties are detected, then a reference to the entity is stored
836
     * there to mark it for an update.
837
     *
838
     * {@link _collectionDeletions}
839
     * If a PersistentCollection has been de-referenced in a fully MANAGED entity,
840
     * then this collection is marked for deletion.
841
     *
842
     * @ignore
843
     *
844
     * @internal Don't call from the outside.
845
     *
846
     * @param ApiMetadata $class  The class descriptor of the entity.
847
     * @param object      $entity The entity for which to compute the changes.
848
     *
849
     * @return void
850
     */
851 5
    public function computeChangeSet(ApiMetadata $class, $entity)
852
    {
853 5
        $oid = spl_object_hash($entity);
854 5
        if (isset($this->readOnlyObjects[$oid])) {
855
            return;
856
        }
857
858 5
        $actualData = [];
859 5
        foreach ($class->getReflectionProperties() as $name => $refProp) {
860 5
            $value = $refProp->getValue($entity);
861 5
            if ($class->isCollectionValuedAssociation($name) && $value !== null) {
862 2
                if ($value instanceof ApiCollection) {
863 1
                    if ($value->getOwner() === $entity) {
864 1
                        continue;
865
                    }
866
                    $value = new ArrayCollection($value->getValues());
867
                }
868
                // If $value is not a Collection then use an ArrayCollection.
869 2
                if (!$value instanceof Collection) {
870
                    $value = new ArrayCollection($value);
871
                }
872 2
                $assoc = $class->getAssociationMapping($name);
873
                // Inject PersistentCollection
874 2
                $value = new ApiCollection(
875 2
                    $this->manager,
876 2
                    $this->manager->getClassMetadata($assoc['target']),
877
                    $value
878 2
                );
879 2
                $value->setOwner($entity, $assoc);
880 2
                $value->setDirty(!$value->isEmpty());
881 2
                $class->getReflectionProperty($name)->setValue($entity, $value);
882 2
                $actualData[$name] = $value;
883 2
                continue;
884
            }
885 5
            if (!$class->isIdentifier($name)) {
886 5
                $actualData[$name] = $value;
887 5
            }
888 5
        }
889 5
        if (!isset($this->originalEntityData[$oid])) {
890
            // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
891
            // These result in an INSERT.
892 5
            $this->originalEntityData[$oid] = $actualData;
893 5
            $changeSet                      = [];
894 5
            foreach ($actualData as $propName => $actualValue) {
895 5 View Code Duplication
                if (!$class->hasAssociation($propName)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
896 5
                    $changeSet[$propName] = [null, $actualValue];
897 5
                    continue;
898
                }
899 5
                $assoc = $class->getAssociationMapping($propName);
900 5
                if ($assoc['isOwningSide'] && $assoc['type'] & ApiMetadata::TO_ONE) {
901 5
                    $changeSet[$propName] = [null, $actualValue];
902 5
                }
903 5
            }
904 5
            $this->entityChangeSets[$oid] = $changeSet;
905 5
        } else {
906
            // Entity is "fully" MANAGED: it was already fully persisted before
907
            // and we have a copy of the original data
908 2
            $originalData           = $this->originalEntityData[$oid];
909 2
            $isChangeTrackingNotify = false;
910 2
            $changeSet              = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
911 2
                ? $this->entityChangeSets[$oid]
912 2
                : [];
913 2
            foreach ($actualData as $propName => $actualValue) {
914
915
                // skip field, its a partially omitted one!
916 2
                if (!(isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
917
                    continue;
918
                }
919 2
                $orgValue = $originalData[$propName];
920
                // skip if value haven't changed
921 2
                if ($orgValue === $actualValue) {
922
923 2
                    continue;
924
                }
925
                // if regular field
926 1 View Code Duplication
                if (!$class->hasAssociation($propName)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
927
                    if ($isChangeTrackingNotify) {
928
                        continue;
929
                    }
930
                    $changeSet[$propName] = [$orgValue, $actualValue];
931
                    continue;
932
                }
933
934 1
                $assoc = $class->getAssociationMapping($propName);
935
                // Persistent collection was exchanged with the "originally"
936
                // created one. This can only mean it was cloned and replaced
937
                // on another entity.
938 1
                if ($actualValue instanceof ApiCollection) {
939
                    $owner = $actualValue->getOwner();
940
                    if ($owner === null) { // cloned
941
                        $actualValue->setOwner($entity, $assoc);
942
                    } else {
943
                        if ($owner !== $entity) { // no clone, we have to fix
944
                            if (!$actualValue->isInitialized()) {
945
                                $actualValue->initialize(); // we have to do this otherwise the cols share state
946
                            }
947
                            $newValue = clone $actualValue;
948
                            $newValue->setOwner($entity, $assoc);
949
                            $class->getReflectionProperty($propName)->setValue($entity, $newValue);
950
                        }
951
                    }
952
                }
953 1
                if ($orgValue instanceof ApiCollection) {
954
                    // A PersistentCollection was de-referenced, so delete it.
955
                    $coid = spl_object_hash($orgValue);
956
                    if (isset($this->collectionDeletions[$coid])) {
957
                        continue;
958
                    }
959
                    $this->collectionDeletions[$coid] = $orgValue;
960
                    $changeSet[$propName]             = $orgValue; // Signal changeset, to-many assocs will be ignored.
961
                    continue;
962
                }
963 1
                if ($assoc['type'] & ApiMetadata::TO_ONE) {
964 1
                    if ($assoc['isOwningSide']) {
965 1
                        $changeSet[$propName] = [$orgValue, $actualValue];
966 1
                    }
967 1
                    if ($orgValue !== null && $assoc['orphanRemoval']) {
968
                        $this->scheduleOrphanRemoval($orgValue);
969
                    }
970 1
                }
971 2
            }
972 2
            if ($changeSet) {
973 1
                $this->entityChangeSets[$oid]   = $changeSet;
974 1
                $this->originalEntityData[$oid] = $actualData;
975 1
                $this->entityUpdates[$oid]      = $entity;
976 1
            }
977
        }
978
        // Look for changes in associations of the entity
979 5
        foreach ($class->getAssociationMappings() as $field => $assoc) {
980 5
            if (($val = $class->getReflectionProperty($field)->getValue($entity)) === null) {
981 5
                continue;
982
            }
983 2
            $this->computeAssociationChanges($assoc, $val);
984 2
            if (!isset($this->entityChangeSets[$oid]) &&
985 2
                $assoc['isOwningSide'] &&
986 2
                $assoc['type'] == ApiMetadata::MANY_TO_MANY &&
987 2
                $val instanceof ApiCollection &&
988
                $val->isDirty()
989 2
            ) {
990
                $this->entityChangeSets[$oid]   = [];
991
                $this->originalEntityData[$oid] = $actualData;
992
                $this->entityUpdates[$oid]      = $entity;
993
            }
994 5
        }
995 5
    }
996
997
    /**
998
     * Computes all the changes that have been done to entities and collections
999
     * since the last commit and stores these changes in the _entityChangeSet map
1000
     * temporarily for access by the persisters, until the UoW commit is finished.
1001
     *
1002
     * @return void
1003
     */
1004 5
    public function computeChangeSets()
1005
    {
1006
        // Compute changes for INSERTed entities first. This must always happen.
1007 5
        $this->computeScheduleInsertsChangeSets();
1008
        // Compute changes for other MANAGED entities. Change tracking policies take effect here.
1009 5
        foreach ($this->identityMap as $className => $entities) {
1010 2
            $class = $this->manager->getClassMetadata($className);
1011
            // Skip class if instances are read-only
1012 2
            if ($class->isReadOnly()) {
1013
                continue;
1014
            }
1015
            // If change tracking is explicit or happens through notification, then only compute
1016
            // changes on entities of that type that are explicitly marked for synchronization.
1017 2
            switch (true) {
1018 2
                case ($class->isChangeTrackingDeferredImplicit()):
1019 2
                    $entitiesToProcess = $entities;
1020 2
                    break;
1021
                case (isset($this->scheduledForSynchronization[$className])):
1022
                    $entitiesToProcess = $this->scheduledForSynchronization[$className];
1023
                    break;
1024
                default:
1025
                    $entitiesToProcess = [];
1026
            }
1027 2
            foreach ($entitiesToProcess as $entity) {
1028
                // Ignore uninitialized proxy objects
1029 2
                if ($entity instanceof Proxy && !$entity->__isInitialized__) {
0 ignored issues
show
Bug introduced by
Accessing __isInitialized__ on the interface Doctrine\Common\Proxy\Proxy suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1030
                    continue;
1031
                }
1032
                // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
1033 2
                $oid = spl_object_hash($entity);
1034 2 View Code Duplication
                if (!isset($this->entityInsertions[$oid]) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1035 2
                    !isset($this->entityDeletions[$oid]) &&
1036 2
                    isset($this->entityStates[$oid])
1037 2
                ) {
1038 2
                    $this->computeChangeSet($class, $entity);
1039 2
                }
1040 2
            }
1041 5
        }
1042 5
    }
1043
1044
    /**
1045
     * INTERNAL:
1046
     * Schedules an orphaned entity for removal. The remove() operation will be
1047
     * invoked on that entity at the beginning of the next commit of this
1048
     * UnitOfWork.
1049
     *
1050
     * @ignore
1051
     *
1052
     * @param object $entity
1053
     *
1054
     * @return void
1055
     */
1056
    public function scheduleOrphanRemoval($entity)
1057
    {
1058
        $this->orphanRemovals[spl_object_hash($entity)] = $entity;
1059
    }
1060
1061 2
    public function loadCollection(ApiCollection $collection)
1062
    {
1063 2
        $assoc     = $collection->getMapping();
1064 2
        $persister = $this->getEntityPersister($assoc['target']);
1065 2
        switch ($assoc['type']) {
1066 2
            case ApiMetadata::ONE_TO_MANY:
1067 2
                $persister->loadOneToManyCollection($assoc, $collection->getOwner(), $collection);
1068 2
                break;
1069 2
        }
1070 2
        $collection->setInitialized(true);
1071 2
    }
1072
1073
    public function getCollectionPersister($association)
1074
    {
1075
        $role = isset($association['cache'])
1076
            ? $association['sourceEntity'] . '::' . $association['fieldName']
1077
            : $association['type'];
1078
        if (array_key_exists($role, $this->collectionPersisters)) {
1079
            return $this->collectionPersisters[$role];
1080
        }
1081
        $this->collectionPersisters[$role] = new CollectionPersister($this->manager);
0 ignored issues
show
Unused Code introduced by
The call to CollectionPersister::__construct() has too many arguments starting with $this->manager.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1082
1083
        return $this->collectionPersisters[$role];
1084
    }
1085
1086
    public function scheduleCollectionDeletion(Collection $collection)
0 ignored issues
show
Unused Code introduced by
The parameter $collection is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1087
    {
1088
    }
1089
1090 2
    public function cancelOrphanRemoval($value)
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1091
    {
1092 2
    }
1093
1094
    /**
1095
     * INTERNAL:
1096
     * Sets a property value of the original data array of an entity.
1097
     *
1098
     * @ignore
1099
     *
1100
     * @param string $oid
1101
     * @param string $property
1102
     * @param mixed  $value
1103
     *
1104
     * @return void
1105
     */
1106 10
    public function setOriginalEntityProperty($oid, $property, $value)
1107
    {
1108 10
        if (!array_key_exists($oid, $this->originalEntityData)) {
1109 10
            $this->originalEntityData[$oid] = new \stdClass();
1110 10
        }
1111
1112 10
        $this->originalEntityData[$oid]->$property = $value;
1113 10
    }
1114
1115
    public function scheduleExtraUpdate($entity, $changeset)
1116
    {
1117
        $oid         = spl_object_hash($entity);
1118
        $extraUpdate = [$entity, $changeset];
1119
        if (isset($this->extraUpdates[$oid])) {
1120
            list(, $changeset2) = $this->extraUpdates[$oid];
1121
            $extraUpdate = [$entity, $changeset + $changeset2];
1122
        }
1123
        $this->extraUpdates[$oid] = $extraUpdate;
1124
    }
1125
1126
    /**
1127
     * Refreshes the state of the given entity from the database, overwriting
1128
     * any local, unpersisted changes.
1129
     *
1130
     * @param object $entity The entity to refresh.
1131
     *
1132
     * @return void
1133
     *
1134
     * @throws InvalidArgumentException If the entity is not MANAGED.
1135
     */
1136
    public function refresh($entity)
1137
    {
1138
        $visited = [];
1139
        $this->doRefresh($entity, $visited);
1140
    }
1141
1142
    /**
1143
     * Clears the UnitOfWork.
1144
     *
1145
     * @param string|null $entityName if given, only entities of this type will get detached.
1146
     *
1147
     * @return void
1148
     */
1149
    public function clear($entityName = null)
1150
    {
1151
        if ($entityName === null) {
1152
            $this->identityMap =
1153
            $this->entityIdentifiers =
1154
            $this->originalEntityData =
1155
            $this->entityChangeSets =
1156
            $this->entityStates =
1157
            $this->scheduledForSynchronization =
1158
            $this->entityInsertions =
1159
            $this->entityUpdates =
1160
            $this->entityDeletions =
1161
            $this->collectionDeletions =
1162
            $this->collectionUpdates =
1163
            $this->extraUpdates =
1164
            $this->readOnlyObjects =
1165
            $this->visitedCollections =
1166
            $this->orphanRemovals = [];
1167
        } else {
1168
            $this->clearIdentityMapForEntityName($entityName);
0 ignored issues
show
Bug introduced by
The method clearIdentityMapForEntityName() does not seem to exist on object<Bankiru\Api\Doctrine\UnitOfWork>.

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...
1169
            $this->clearEntityInsertionsForEntityName($entityName);
0 ignored issues
show
Bug introduced by
The method clearEntityInsertionsForEntityName() does not seem to exist on object<Bankiru\Api\Doctrine\UnitOfWork>.

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...
1170
        }
1171
    }
1172
1173
    /**
1174
     * @param PersistentCollection $coll
1175
     *
1176
     * @return bool
1177
     */
1178
    public function isCollectionScheduledForDeletion(PersistentCollection $coll)
1179
    {
1180
        return isset($this->collectionDeletions[spl_object_hash($coll)]);
1181
    }
1182
1183
    /**
1184
     * Schedules an entity for dirty-checking at commit-time.
1185
     *
1186
     * @param object $entity The entity to schedule for dirty-checking.
1187
     *
1188
     * @return void
1189
     *
1190
     * @todo Rename: scheduleForSynchronization
1191
     */
1192
    public function scheduleForDirtyCheck($entity)
1193
    {
1194
        $rootClassName                                                               =
1195
            $this->manager->getClassMetadata(get_class($entity))->getRootEntityName();
1196
        $this->scheduledForSynchronization[$rootClassName][spl_object_hash($entity)] = $entity;
1197
    }
1198
1199
    /**
1200
     * Deletes an entity as part of the current unit of work.
1201
     *
1202
     * @param object $entity The entity to remove.
1203
     *
1204
     * @return void
1205
     */
1206
    public function remove($entity)
1207
    {
1208
        $visited = [];
1209
        $this->doRemove($entity, $visited);
1210
    }
1211
1212
    /**
1213
     * Merges the state of the given detached entity into this UnitOfWork.
1214
     *
1215
     * @param object $entity
1216
     *
1217
     * @return object The managed copy of the entity.
1218
     */
1219
    public function merge($entity)
1220
    {
1221
        $visited = [];
1222
1223
        return $this->doMerge($entity, $visited);
1224
    }
1225
1226
    /**
1227
     * Detaches an entity from the persistence management. It's persistence will
1228
     * no longer be managed by Doctrine.
1229
     *
1230
     * @param object $entity The entity to detach.
1231
     *
1232
     * @return void
1233
     */
1234
    public function detach($entity)
1235
    {
1236
        $visited = [];
1237
        $this->doDetach($entity, $visited);
1238
    }
1239
1240
    /**
1241
     * Helper method to show an object as string.
1242
     *
1243
     * @param object $obj
1244
     *
1245
     * @return string
1246
     */
1247
    private static function objToStr($obj)
1248
    {
1249
        return method_exists($obj, '__toString') ? (string)$obj : get_class($obj) . '@' . spl_object_hash($obj);
1250
    }
1251
1252
    /**
1253
     * @param ApiMetadata $class
1254
     *
1255
     * @return \Doctrine\Common\Persistence\ObjectManagerAware|object
1256
     */
1257 12
    private function newInstance(ApiMetadata $class)
1258
    {
1259 12
        $entity = $class->newInstance();
1260
1261 12
        if ($entity instanceof ObjectManagerAware) {
1262
            $entity->injectObjectManager($this->manager, $class);
1263
        }
1264
1265 12
        return $entity;
1266
    }
1267
1268
    /**
1269
     * @param ApiMetadata $classMetadata
1270
     *
1271
     * @return EntityDataCacheInterface
1272
     */
1273 19
    private function createEntityCache(ApiMetadata $classMetadata)
1274
    {
1275 19
        $configuration = $this->manager->getConfiguration()->getCacheConfiguration($classMetadata->getName());
1276 19
        $cache         = new VoidEntityCache($classMetadata);
1277 19
        if ($configuration->isEnabled() && $this->manager->getConfiguration()->getApiCache()) {
1278
            $cache =
1279 1
                new LoggingCache(
1280 1
                    new ApiEntityCache(
1281 1
                        $this->manager->getConfiguration()->getApiCache(),
1282 1
                        $classMetadata,
1283
                        $configuration
1284 1
                    ),
1285 1
                    $this->manager->getConfiguration()->getApiCacheLogger()
1286 1
                );
1287
1288 1
            return $cache;
1289
        }
1290
1291 18
        return $cache;
1292
    }
1293
1294
    /**
1295
     * @param ApiMetadata $classMetadata
1296
     *
1297
     * @return CrudsApiInterface
1298
     */
1299 19
    private function createApi(ApiMetadata $classMetadata)
1300
    {
1301 19
        $client = $this->manager->getConfiguration()->getClientRegistry()->get($classMetadata->getClientName());
1302
1303 19
        $api = $this->manager
1304 19
            ->getConfiguration()
1305 19
            ->getFactoryRegistry()
1306 19
            ->create(
1307 19
                $classMetadata->getApiFactory(),
1308 19
                $client,
1309
                $classMetadata
1310 19
            );
1311
1312 19
        return $api;
1313
    }
1314
1315 5
    private function doPersist($entity, $visited)
1316
    {
1317 5
        $oid = spl_object_hash($entity);
1318 5
        if (isset($visited[$oid])) {
1319
            return; // Prevent infinite recursion
1320
        }
1321 5
        $visited[$oid] = $entity; // Mark visited
1322 5
        $class         = $this->manager->getClassMetadata(get_class($entity));
1323
        // We assume NEW, so DETACHED entities result in an exception on flush (constraint violation).
1324
        // If we would detect DETACHED here we would throw an exception anyway with the same
1325
        // consequences (not recoverable/programming error), so just assuming NEW here
1326
        // lets us avoid some database lookups for entities with natural identifiers.
1327 5
        $entityState = $this->getEntityState($entity, self::STATE_NEW);
1328
        switch ($entityState) {
1329 5
            case self::STATE_MANAGED:
1330
                $this->scheduleForDirtyCheck($entity);
1331
                break;
1332 5
            case self::STATE_NEW:
1333 5
                $this->persistNew($class, $entity);
1334 5
                break;
1335
            case self::STATE_REMOVED:
1336
                // Entity becomes managed again
1337
                unset($this->entityDeletions[$oid]);
1338
                $this->addToIdentityMap($entity);
1339
                $this->entityStates[$oid] = self::STATE_MANAGED;
1340
                break;
1341
            case self::STATE_DETACHED:
1342
                // Can actually not happen right now since we assume STATE_NEW.
1343
                throw new \InvalidArgumentException('Detached entity cannot be persisted');
1344
            default:
1345
                throw new \UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
1346
        }
1347 5
        $this->cascadePersist($entity, $visited);
1348 5
    }
1349
1350
    /**
1351
     * Cascades the save operation to associated entities.
1352
     *
1353
     * @param object $entity
1354
     * @param array  $visited
1355
     *
1356
     * @return void
1357
     * @throws \InvalidArgumentException
1358
     * @throws MappingException
1359
     */
1360 5
    private function cascadePersist($entity, array &$visited)
1361
    {
1362 5
        $class               = $this->manager->getClassMetadata(get_class($entity));
1363 5
        $associationMappings = [];
1364 5
        foreach ($class->getAssociationNames() as $name) {
1365 5
            $assoc = $class->getAssociationMapping($name);
1366 5
            if ($assoc['isCascadePersist']) {
1367
                $associationMappings[$name] = $assoc;
1368
            }
1369 5
        }
1370 5
        foreach ($associationMappings as $assoc) {
1371
            $relatedEntities = $class->getReflectionProperty($assoc['field'])->getValue($entity);
1372
            switch (true) {
1373
                case ($relatedEntities instanceof ApiCollection):
1374
                    // Unwrap so that foreach() does not initialize
1375
                    $relatedEntities = $relatedEntities->unwrap();
1376
                // break; is commented intentionally!
1377
                case ($relatedEntities instanceof Collection):
1378
                case (is_array($relatedEntities)):
1379
                    if (($assoc['type'] & ApiMetadata::TO_MANY) <= 0) {
1380
                        throw new \InvalidArgumentException('Invalid association for cascade');
1381
                    }
1382
                    foreach ($relatedEntities as $relatedEntity) {
1383
                        $this->doPersist($relatedEntity, $visited);
1384
                    }
1385
                    break;
1386
                case ($relatedEntities !== null):
1387
                    if (!$relatedEntities instanceof $assoc['target']) {
1388
                        throw new \InvalidArgumentException('Invalid association for cascade');
1389
                    }
1390
                    $this->doPersist($relatedEntities, $visited);
1391
                    break;
1392
                default:
1393
                    // Do nothing
1394
            }
1395 5
        }
1396 5
    }
1397
1398
    /**
1399
     * @param ApiMetadata $class
1400
     * @param object      $entity
1401
     *
1402
     * @return void
1403
     */
1404 5
    private function persistNew($class, $entity)
0 ignored issues
show
Unused Code introduced by
The parameter $class is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1405
    {
1406 5
        $oid = spl_object_hash($entity);
1407
        //        $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::prePersist);
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1408
        //        if ($invoke !== ListenersInvoker::INVOKE_NONE) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1409
        //            $this->listenersInvoker->invoke($class, Events::prePersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1410
        //        }
1411
        //        $idGen = $class->idGenerator;
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1412
        //        if ( ! $idGen->isPostInsertGenerator()) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1413
        //            $idValue = $idGen->generate($this->em, $entity);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1414
        //            if ( ! $idGen instanceof \Doctrine\ORM\Id\AssignedGenerator) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1415
        //                $idValue = array($class->identifier[0] => $idValue);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1416
        //                $class->setIdentifierValues($entity, $idValue);
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1417
        //            }
1418
        //            $this->entityIdentifiers[$oid] = $idValue;
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1419
        //        }
1420 5
        $this->entityStates[$oid] = self::STATE_MANAGED;
1421 5
        $this->scheduleForInsert($entity);
1422 5
    }
1423
1424
    /**
1425
     * Gets the commit order.
1426
     *
1427
     * @param array|null $entityChangeSet
1428
     *
1429
     * @return array
1430
     */
1431 5
    private function getCommitOrder(array $entityChangeSet = null)
1432
    {
1433 5
        if ($entityChangeSet === null) {
1434 5
            $entityChangeSet = array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions);
1435 5
        }
1436 5
        $calc = $this->getCommitOrderCalculator();
1437
        // See if there are any new classes in the changeset, that are not in the
1438
        // commit order graph yet (don't have a node).
1439
        // We have to inspect changeSet to be able to correctly build dependencies.
1440
        // It is not possible to use IdentityMap here because post inserted ids
1441
        // are not yet available.
1442
        /** @var ApiMetadata[] $newNodes */
1443 5
        $newNodes = [];
1444 5
        foreach ((array)$entityChangeSet as $entity) {
1445 5
            $class = $this->manager->getClassMetadata(get_class($entity));
1446 5
            if ($calc->hasNode($class->getName())) {
1447
                continue;
1448
            }
1449 5
            $calc->addNode($class->getName(), $class);
1450 5
            $newNodes[] = $class;
1451 5
        }
1452
        // Calculate dependencies for new nodes
1453 5
        while ($class = array_pop($newNodes)) {
1454 5
            foreach ($class->getAssociationMappings() as $assoc) {
1455 5
                if (!($assoc['isOwningSide'] && $assoc['type'] & ApiMetadata::TO_ONE)) {
1456 5
                    continue;
1457
                }
1458 5
                $targetClass = $this->manager->getClassMetadata($assoc['target']);
1459 5
                if (!$calc->hasNode($targetClass->getName())) {
1460 3
                    $calc->addNode($targetClass->getName(), $targetClass);
1461 3
                    $newNodes[] = $targetClass;
1462 3
                }
1463 5
                $calc->addDependency($targetClass->getName(), $class->name, (int)empty($assoc['nullable']));
1464
                // If the target class has mapped subclasses, these share the same dependency.
1465 5
                if (!$targetClass->getSubclasses()) {
1466 5
                    continue;
1467
                }
1468
                foreach ($targetClass->getSubclasses() as $subClassName) {
1469
                    $targetSubClass = $this->manager->getClassMetadata($subClassName);
1470
                    if (!$calc->hasNode($subClassName)) {
1471
                        $calc->addNode($targetSubClass->name, $targetSubClass);
0 ignored issues
show
Bug introduced by
Accessing name on the interface Bankiru\Api\Doctrine\Mapping\ApiMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1472
                        $newNodes[] = $targetSubClass;
1473
                    }
1474
                    $calc->addDependency($targetSubClass->name, $class->name, 1);
0 ignored issues
show
Bug introduced by
Accessing name on the interface Bankiru\Api\Doctrine\Mapping\ApiMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1475
                }
1476 5
            }
1477 5
        }
1478
1479 5
        return $calc->sort();
1480
    }
1481
1482 5
    private function getCommitOrderCalculator()
1483
    {
1484 5
        return new Utility\CommitOrderCalculator();
1485
    }
1486
1487
    /**
1488
     * Only flushes the given entity according to a ruleset that keeps the UoW consistent.
1489
     *
1490
     * 1. All entities scheduled for insertion, (orphan) removals and changes in collections are processed as well!
1491
     * 2. Read Only entities are skipped.
1492
     * 3. Proxies are skipped.
1493
     * 4. Only if entity is properly managed.
1494
     *
1495
     * @param object $entity
1496
     *
1497
     * @return void
1498
     *
1499
     * @throws \InvalidArgumentException
1500
     */
1501
    private function computeSingleEntityChangeSet($entity)
1502
    {
1503
        $state = $this->getEntityState($entity);
1504
        if ($state !== self::STATE_MANAGED && $state !== self::STATE_REMOVED) {
1505
            throw new \InvalidArgumentException(
1506
                "Entity has to be managed or scheduled for removal for single computation " . self::objToStr($entity)
1507
            );
1508
        }
1509
        $class = $this->manager->getClassMetadata(get_class($entity));
1510
        // Compute changes for INSERTed entities first. This must always happen even in this case.
1511
        $this->computeScheduleInsertsChangeSets();
1512
        if ($class->isReadOnly()) {
1513
            return;
1514
        }
1515
        // Ignore uninitialized proxy objects
1516
        if ($entity instanceof Proxy && !$entity->__isInitialized__) {
0 ignored issues
show
Bug introduced by
Accessing __isInitialized__ on the interface Doctrine\Common\Proxy\Proxy suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1517
            return;
1518
        }
1519
        // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
1520
        $oid = spl_object_hash($entity);
1521 View Code Duplication
        if (!isset($this->entityInsertions[$oid]) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1522
            !isset($this->entityDeletions[$oid]) &&
1523
            isset($this->entityStates[$oid])
1524
        ) {
1525
            $this->computeChangeSet($class, $entity);
1526
        }
1527
    }
1528
1529
    /**
1530
     * Computes the changesets of all entities scheduled for insertion.
1531
     *
1532
     * @return void
1533
     */
1534 5
    private function computeScheduleInsertsChangeSets()
1535
    {
1536 5
        foreach ($this->entityInsertions as $entity) {
1537 5
            $class = $this->manager->getClassMetadata(get_class($entity));
1538 5
            $this->computeChangeSet($class, $entity);
1539 5
        }
1540 5
    }
1541
1542
    /**
1543
     * Computes the changes of an association.
1544
     *
1545
     * @param array $assoc The association mapping.
1546
     * @param mixed $value The value of the association.
1547
     *
1548
     * @throws \InvalidArgumentException
1549
     * @throws \UnexpectedValueException
1550
     *
1551
     * @return void
1552
     */
1553 2
    private function computeAssociationChanges($assoc, $value)
1554
    {
1555 2
        if ($value instanceof Proxy && !$value->__isInitialized__) {
0 ignored issues
show
Bug introduced by
Accessing __isInitialized__ on the interface Doctrine\Common\Proxy\Proxy suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1556
            return;
1557
        }
1558 2
        if ($value instanceof ApiCollection && $value->isDirty()) {
1559 2
            $coid                            = spl_object_hash($value);
1560 2
            $this->collectionUpdates[$coid]  = $value;
1561 2
            $this->visitedCollections[$coid] = $value;
1562 2
        }
1563
        // Look through the entities, and in any of their associations,
1564
        // for transient (new) entities, recursively. ("Persistence by reachability")
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1565
        // Unwrap. Uninitialized collections will simply be empty.
1566 2
        $unwrappedValue  = ($assoc['type'] & ApiMetadata::TO_ONE) ? [$value] : $value->unwrap();
1567 2
        $targetClass     = $this->manager->getClassMetadata($assoc['target']);
1568 2
        $targetClassName = $targetClass->getName();
1569 2
        foreach ($unwrappedValue as $key => $entry) {
1570 2
            if (!($entry instanceof $targetClassName)) {
1571
                throw new \InvalidArgumentException('Invalid association');
1572
            }
1573 2
            $state = $this->getEntityState($entry, self::STATE_NEW);
1574 2
            if (!($entry instanceof $assoc['target'])) {
1575
                throw new \UnexpectedValueException('Unexpected association');
1576
            }
1577
            switch ($state) {
1578 2
                case self::STATE_NEW:
1579
                    if (!$assoc['isCascadePersist']) {
1580
                        throw new \InvalidArgumentException('New entity through relationship');
1581
                    }
1582
                    $this->persistNew($targetClass, $entry);
1583
                    $this->computeChangeSet($targetClass, $entry);
1584
                    break;
1585 2
                case self::STATE_REMOVED:
1586
                    // Consume the $value as array (it's either an array or an ArrayAccess)
1587
                    // and remove the element from Collection.
1588
                    if ($assoc['type'] & ApiMetadata::TO_MANY) {
1589
                        unset($value[$key]);
1590
                    }
1591
                    break;
1592 2
                case self::STATE_DETACHED:
1593
                    // Can actually not happen right now as we assume STATE_NEW,
1594
                    // so the exception will be raised from the DBAL layer (constraint violation).
1595
                    throw new \InvalidArgumentException('Detached entity through relationship');
1596
                    break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1597 2
                default:
1598
                    // MANAGED associated entities are already taken into account
1599
                    // during changeset calculation anyway, since they are in the identity map.
1600 2
            }
1601 2
        }
1602 2
    }
1603
1604 5
    private function executeInserts(ApiMetadata $class)
1605
    {
1606 5
        $className = $class->getName();
1607 5
        $persister = $this->getEntityPersister($className);
1608 5
        foreach ($this->entityInsertions as $oid => $entity) {
1609 5
            if ($this->manager->getClassMetadata(get_class($entity))->getName() !== $className) {
1610 5
                continue;
1611
            }
1612 5
            $persister->pushNewEntity($entity);
1613 5
            unset($this->entityInsertions[$oid]);
1614 5
        }
1615 5
        $postInsertIds = $persister->flushNewEntities();
1616 5
        if ($postInsertIds) {
1617
            // Persister returned post-insert IDs
1618 5
            foreach ($postInsertIds as $postInsertId) {
1619 5
                $id     = $postInsertId['generatedId'];
1620 5
                $entity = $postInsertId['entity'];
1621 5
                $oid    = spl_object_hash($entity);
1622
1623 5
                if ($id instanceof \stdClass) {
1624
                    $id = (array)$id;
1625
                }
1626 5
                if (!is_array($id)) {
1627 2
                    $id = [$class->getApiFieldName($class->getIdentifierFieldNames()[0]) => $id];
1628 2
                }
1629
1630 5
                $idValues = [];
1631 5
                foreach ((array)$id as $apiIdField => $idValue) {
1632 5
                    $idName   = $class->getFieldName($apiIdField);
1633 5
                    $typeName = $class->getTypeOfField($idName);
1634 5
                    $type     = $this->manager->getConfiguration()->getTypeRegistry()->get($typeName);
1635 5
                    $idValue  = $type->toApiValue($idValue);
1636 5
                    $class->getReflectionProperty($idName)->setValue($entity, $idValue);
1637 5
                    $idValues[$idName] =  $idValue;
1638 5
                    $this->originalEntityData[$oid][$idName] = $idValue;
1639 5
                }
1640
1641 5
                $this->entityIdentifiers[$oid]  = $idValues;
1642 5
                $this->entityStates[$oid]       = self::STATE_MANAGED;
1643 5
                $this->addToIdentityMap($entity);
1644 5
            }
1645 5
        }
1646 5
    }
1647
1648 1
    private function executeUpdates($class)
1649
    {
1650 1
        $className = $class->name;
1651 1
        $persister = $this->getEntityPersister($className);
1652 1
        foreach ($this->entityUpdates as $oid => $entity) {
1653 1
            if ($this->manager->getClassMetadata(get_class($entity))->getName() !== $className) {
1654 1
                continue;
1655
            }
1656 1
            $this->recomputeSingleEntityChangeSet($class, $entity);
1657
1658 1
            if (!empty($this->entityChangeSets[$oid])) {
1659 1
                $persister->update($entity);
1660 1
            }
1661 1
            unset($this->entityUpdates[$oid]);
1662 1
        }
1663 1
    }
1664
1665
    /**
1666
     * Executes a refresh operation on an entity.
1667
     *
1668
     * @param object $entity  The entity to refresh.
1669
     * @param array  $visited The already visited entities during cascades.
1670
     *
1671
     * @return void
1672
     *
1673
     * @throws \InvalidArgumentException If the entity is not MANAGED.
1674
     */
1675
    private function doRefresh($entity, array &$visited)
1676
    {
1677
        $oid = spl_object_hash($entity);
1678
        if (isset($visited[$oid])) {
1679
            return; // Prevent infinite recursion
1680
        }
1681
        $visited[$oid] = $entity; // mark visited
1682
        $class         = $this->manager->getClassMetadata(get_class($entity));
1683
        if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
1684
            throw new \InvalidArgumentException('Entity not managed');
1685
        }
1686
        $this->getEntityPersister($class->getName())->refresh(
1687
            array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
1688
            $entity
1689
        );
1690
        $this->cascadeRefresh($entity, $visited);
1691
    }
1692
1693
    /**
1694
     * Cascades a refresh operation to associated entities.
1695
     *
1696
     * @param object $entity
1697
     * @param array  $visited
1698
     *
1699
     * @return void
1700
     */
1701 View Code Duplication
    private function cascadeRefresh($entity, array &$visited)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1702
    {
1703
        $class               = $this->manager->getClassMetadata(get_class($entity));
1704
        $associationMappings = array_filter(
1705
            $class->getAssociationMappings(),
1706
            function ($assoc) {
1707
                return $assoc['isCascadeRefresh'];
1708
            }
1709
        );
1710
        foreach ($associationMappings as $assoc) {
1711
            $relatedEntities = $class->getReflectionProperty($assoc['fieldName'])->getValue($entity);
1712
            switch (true) {
1713
                case ($relatedEntities instanceof ApiCollection):
1714
                    // Unwrap so that foreach() does not initialize
1715
                    $relatedEntities = $relatedEntities->unwrap();
1716
                // break; is commented intentionally!
1717
                case ($relatedEntities instanceof Collection):
1718
                case (is_array($relatedEntities)):
1719
                    foreach ($relatedEntities as $relatedEntity) {
1720
                        $this->doRefresh($relatedEntity, $visited);
1721
                    }
1722
                    break;
1723
                case ($relatedEntities !== null):
1724
                    $this->doRefresh($relatedEntities, $visited);
1725
                    break;
1726
                default:
1727
                    // Do nothing
1728
            }
1729
        }
1730
    }
1731
1732
    /**
1733
     * Cascades a detach operation to associated entities.
1734
     *
1735
     * @param object $entity
1736
     * @param array  $visited
1737
     *
1738
     * @return void
1739
     */
1740 View Code Duplication
    private function cascadeDetach($entity, array &$visited)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1741
    {
1742
        $class               = $this->manager->getClassMetadata(get_class($entity));
1743
        $associationMappings = array_filter(
1744
            $class->getAssociationMappings(),
1745
            function ($assoc) {
1746
                return $assoc['isCascadeDetach'];
1747
            }
1748
        );
1749
        foreach ($associationMappings as $assoc) {
1750
            $relatedEntities = $class->getReflectionProperty($assoc['fieldName'])->getValue($entity);
1751
            switch (true) {
1752
                case ($relatedEntities instanceof ApiCollection):
1753
                    // Unwrap so that foreach() does not initialize
1754
                    $relatedEntities = $relatedEntities->unwrap();
1755
                // break; is commented intentionally!
1756
                case ($relatedEntities instanceof Collection):
1757
                case (is_array($relatedEntities)):
1758
                    foreach ($relatedEntities as $relatedEntity) {
1759
                        $this->doDetach($relatedEntity, $visited);
1760
                    }
1761
                    break;
1762
                case ($relatedEntities !== null):
1763
                    $this->doDetach($relatedEntities, $visited);
1764
                    break;
1765
                default:
1766
                    // Do nothing
1767
            }
1768
        }
1769
    }
1770
1771
    /**
1772
     * Cascades a merge operation to associated entities.
1773
     *
1774
     * @param object $entity
1775
     * @param object $managedCopy
1776
     * @param array  $visited
1777
     *
1778
     * @return void
1779
     */
1780
    private function cascadeMerge($entity, $managedCopy, array &$visited)
1781
    {
1782
        $class               = $this->manager->getClassMetadata(get_class($entity));
1783
        $associationMappings = array_filter(
1784
            $class->getAssociationMappings(),
1785
            function ($assoc) {
1786
                return $assoc['isCascadeMerge'];
1787
            }
1788
        );
1789
        foreach ($associationMappings as $assoc) {
1790
            $relatedEntities = $class->getReflectionProperty($assoc['field'])->getValue($entity);
1791
            if ($relatedEntities instanceof Collection) {
1792
                if ($relatedEntities === $class->getReflectionProperty($assoc['field'])->getValue($managedCopy)) {
1793
                    continue;
1794
                }
1795
                if ($relatedEntities instanceof ApiCollection) {
1796
                    // Unwrap so that foreach() does not initialize
1797
                    $relatedEntities = $relatedEntities->unwrap();
1798
                }
1799
                foreach ($relatedEntities as $relatedEntity) {
1800
                    $this->doMerge($relatedEntity, $visited, $managedCopy, $assoc);
1801
                }
1802
            } else {
1803
                if ($relatedEntities !== null) {
1804
                    $this->doMerge($relatedEntities, $visited, $managedCopy, $assoc);
1805
                }
1806
            }
1807
        }
1808
    }
1809
1810
    /**
1811
     * Cascades the delete operation to associated entities.
1812
     *
1813
     * @param object $entity
1814
     * @param array  $visited
1815
     *
1816
     * @return void
1817
     */
1818
    private function cascadeRemove($entity, array &$visited)
1819
    {
1820
        $class               = $this->manager->getClassMetadata(get_class($entity));
1821
        $associationMappings = array_filter(
1822
            $class->getAssociationMappings(),
1823
            function ($assoc) {
1824
                return $assoc['isCascadeRemove'];
1825
            }
1826
        );
1827
        $entitiesToCascade   = [];
1828
        foreach ($associationMappings as $assoc) {
1829
            if ($entity instanceof Proxy && !$entity->__isInitialized__) {
0 ignored issues
show
Bug introduced by
Accessing __isInitialized__ on the interface Doctrine\Common\Proxy\Proxy suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1830
                $entity->__load();
1831
            }
1832
            $relatedEntities = $class->getReflectionProperty($assoc['fieldName'])->getValue($entity);
1833
            switch (true) {
1834
                case ($relatedEntities instanceof Collection):
1835
                case (is_array($relatedEntities)):
1836
                    // If its a PersistentCollection initialization is intended! No unwrap!
1837
                    foreach ($relatedEntities as $relatedEntity) {
1838
                        $entitiesToCascade[] = $relatedEntity;
1839
                    }
1840
                    break;
1841
                case ($relatedEntities !== null):
1842
                    $entitiesToCascade[] = $relatedEntities;
1843
                    break;
1844
                default:
1845
                    // Do nothing
1846
            }
1847
        }
1848
        foreach ($entitiesToCascade as $relatedEntity) {
1849
            $this->doRemove($relatedEntity, $visited);
1850
        }
1851
    }
1852
1853
    /**
1854
     * Executes any extra updates that have been scheduled.
1855
     */
1856
    private function executeExtraUpdates()
1857
    {
1858
        foreach ($this->extraUpdates as $oid => $update) {
1859
            list ($entity, $changeset) = $update;
1860
            $this->entityChangeSets[$oid] = $changeset;
1861
            $this->getEntityPersister(get_class($entity))->update($entity);
1862
        }
1863
        $this->extraUpdates = [];
1864
    }
1865
1866
    private function executeDeletions(ApiMetadata $class)
1867
    {
1868
        $className = $class->getName();
1869
        $persister = $this->getEntityPersister($className);
1870
        foreach ($this->entityDeletions as $oid => $entity) {
1871
            if ($this->manager->getClassMetadata(get_class($entity))->getName() !== $className) {
1872
                continue;
1873
            }
1874
            $persister->delete($entity);
1875
            unset(
1876
                $this->entityDeletions[$oid],
1877
                $this->entityIdentifiers[$oid],
1878
                $this->originalEntityData[$oid],
1879
                $this->entityStates[$oid]
1880
            );
1881
            // Entity with this $oid after deletion treated as NEW, even if the $oid
1882
            // is obtained by a new entity because the old one went out of scope.
1883
            //$this->entityStates[$oid] = self::STATE_NEW;
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1884
            //            if ( ! $class->isIdentifierNatural()) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1885
            //                $class->getReflectionProperty($class->getIdentifierFieldNames()[0])->setValue($entity, null);
0 ignored issues
show
Unused Code Comprehensibility introduced by
79% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1886
            //            }
1887
        }
1888
    }
1889
1890
    /**
1891
     * @param object $entity
1892
     * @param object $managedCopy
1893
     */
1894
    private function mergeEntityStateIntoManagedCopy($entity, $managedCopy)
1895
    {
1896
        $class = $this->manager->getClassMetadata(get_class($entity));
1897
        foreach ($this->reflectionPropertiesGetter->getProperties($class->getName()) as $prop) {
1898
            $name = $prop->name;
1899
            $prop->setAccessible(true);
1900
            if ($class->hasAssociation($name)) {
1901
                if (!$class->isIdentifier($name)) {
1902
                    $prop->setValue($managedCopy, $prop->getValue($entity));
1903
                }
1904
            } else {
1905
                $assoc2 = $class->getAssociationMapping($name);
1906
                if ($assoc2['type'] & ApiMetadata::TO_ONE) {
1907
                    $other = $prop->getValue($entity);
1908
                    if ($other === null) {
1909
                        $prop->setValue($managedCopy, null);
1910
                    } else {
1911
                        if ($other instanceof Proxy && !$other->__isInitialized()) {
1912
                            // do not merge fields marked lazy that have not been fetched.
1913
                            continue;
1914
                        }
1915
                        if (!$assoc2['isCascadeMerge']) {
1916
                            if ($this->getEntityState($other) === self::STATE_DETACHED) {
1917
                                $targetClass = $this->manager->getClassMetadata($assoc2['targetEntity']);
1918
                                $relatedId   = $targetClass->getIdentifierValues($other);
1919
                                if ($targetClass->getSubclasses()) {
1920
                                    $other = $this->manager->find($targetClass->getName(), $relatedId);
1921
                                } else {
1922
                                    $other = $this->manager->getProxyFactory()->getProxy(
1923
                                        $assoc2['targetEntity'],
1924
                                        $relatedId
1925
                                    );
1926
                                    $this->registerManaged($other, $relatedId, []);
0 ignored issues
show
Documentation introduced by
array() is of type array, but the function expects a null|object<stdClass>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1927
                                }
1928
                            }
1929
                            $prop->setValue($managedCopy, $other);
1930
                        }
1931
                    }
1932
                } else {
1933
                    $mergeCol = $prop->getValue($entity);
1934
                    if ($mergeCol instanceof ApiCollection && !$mergeCol->isInitialized()) {
1935
                        // do not merge fields marked lazy that have not been fetched.
1936
                        // keep the lazy persistent collection of the managed copy.
1937
                        continue;
1938
                    }
1939
                    $managedCol = $prop->getValue($managedCopy);
1940
                    if (!$managedCol) {
1941
                        $managedCol = new ApiCollection(
1942
                            $this->manager,
1943
                            $this->manager->getClassMetadata($assoc2['target']),
1944
                            new ArrayCollection
1945
                        );
1946
                        $managedCol->setOwner($managedCopy, $assoc2);
1947
                        $prop->setValue($managedCopy, $managedCol);
1948
                    }
1949
                    if ($assoc2['isCascadeMerge']) {
1950
                        $managedCol->initialize();
1951
                        // clear and set dirty a managed collection if its not also the same collection to merge from.
1952
                        if (!$managedCol->isEmpty() && $managedCol !== $mergeCol) {
1953
                            $managedCol->unwrap()->clear();
1954
                            $managedCol->setDirty(true);
1955
                            if ($assoc2['isOwningSide']
1956
                                && $assoc2['type'] == ApiMetadata::MANY_TO_MANY
1957
                                && $class->isChangeTrackingNotify()
1958
                            ) {
1959
                                $this->scheduleForDirtyCheck($managedCopy);
1960
                            }
1961
                        }
1962
                    }
1963
                }
1964
            }
1965
            if ($class->isChangeTrackingNotify()) {
1966
                // Just treat all properties as changed, there is no other choice.
1967
                $this->propertyChanged($managedCopy, $name, null, $prop->getValue($managedCopy));
1968
            }
1969
        }
1970
    }
1971
1972
    /**
1973
     * Deletes an entity as part of the current unit of work.
1974
     *
1975
     * This method is internally called during delete() cascades as it tracks
1976
     * the already visited entities to prevent infinite recursions.
1977
     *
1978
     * @param object $entity  The entity to delete.
1979
     * @param array  $visited The map of the already visited entities.
1980
     *
1981
     * @return void
1982
     *
1983
     * @throws \InvalidArgumentException If the instance is a detached entity.
1984
     * @throws \UnexpectedValueException
1985
     */
1986
    private function doRemove($entity, array &$visited)
1987
    {
1988
        $oid = spl_object_hash($entity);
1989
        if (isset($visited[$oid])) {
1990
            return; // Prevent infinite recursion
1991
        }
1992
        $visited[$oid] = $entity; // mark visited
1993
        // Cascade first, because scheduleForDelete() removes the entity from the identity map, which
1994
        // can cause problems when a lazy proxy has to be initialized for the cascade operation.
1995
        $this->cascadeRemove($entity, $visited);
1996
        $class       = $this->manager->getClassMetadata(get_class($entity));
0 ignored issues
show
Unused Code introduced by
$class is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1997
        $entityState = $this->getEntityState($entity);
1998
        switch ($entityState) {
1999
            case self::STATE_NEW:
2000
            case self::STATE_REMOVED:
2001
                // nothing to do
2002
                break;
2003
            case self::STATE_MANAGED:
2004
                $this->scheduleForDelete($entity);
2005
                break;
2006
            case self::STATE_DETACHED:
2007
                throw new \InvalidArgumentException('Detached entity cannot be removed');
2008
            default:
2009
                throw new \UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
2010
        }
2011
    }
2012
2013
    /**
2014
     * Tests if an entity is loaded - must either be a loaded proxy or not a proxy
2015
     *
2016
     * @param object $entity
2017
     *
2018
     * @return bool
2019
     */
2020
    private function isLoaded($entity)
2021
    {
2022
        return !($entity instanceof Proxy) || $entity->__isInitialized();
2023
    }
2024
2025
    /**
2026
     * Sets/adds associated managed copies into the previous entity's association field
2027
     *
2028
     * @param object $entity
2029
     * @param array  $association
2030
     * @param object $previousManagedCopy
2031
     * @param object $managedCopy
2032
     *
2033
     * @return void
2034
     */
2035
    private function updateAssociationWithMergedEntity($entity, array $association, $previousManagedCopy, $managedCopy)
2036
    {
2037
        $assocField = $association['fieldName'];
2038
        $prevClass  = $this->manager->getClassMetadata(get_class($previousManagedCopy));
2039
        if ($association['type'] & ApiMetadata::TO_ONE) {
2040
            $prevClass->getReflectionProperty($assocField)->setValue($previousManagedCopy, $managedCopy);
2041
2042
            return;
2043
        }
2044
        /** @var array $value */
2045
        $value   = $prevClass->getReflectionProperty($assocField)->getValue($previousManagedCopy);
2046
        $value[] = $managedCopy;
2047
        if ($association['type'] == ApiMetadata::ONE_TO_MANY) {
2048
            $class = $this->manager->getClassMetadata(get_class($entity));
2049
            $class->getReflectionProperty($association['mappedBy'])->setValue($managedCopy, $previousManagedCopy);
2050
        }
2051
    }
2052
2053
    /**
2054
     * Executes a merge operation on an entity.
2055
     *
2056
     * @param object      $entity
2057
     * @param array       $visited
2058
     * @param object|null $prevManagedCopy
2059
     * @param array|null  $assoc
2060
     *
2061
     * @return object The managed copy of the entity.
2062
     *
2063
     * @throws \InvalidArgumentException If the entity instance is NEW.
2064
     * @throws \OutOfBoundsException
2065
     */
2066
    private function doMerge($entity, array &$visited, $prevManagedCopy = null, array $assoc = [])
2067
    {
2068
        $oid = spl_object_hash($entity);
2069
        if (isset($visited[$oid])) {
2070
            $managedCopy = $visited[$oid];
2071
            if ($prevManagedCopy !== null) {
2072
                $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, $managedCopy);
2073
            }
2074
2075
            return $managedCopy;
2076
        }
2077
        $class = $this->manager->getClassMetadata(get_class($entity));
2078
        // First we assume DETACHED, although it can still be NEW but we can avoid
2079
        // an extra db-roundtrip this way. If it is not MANAGED but has an identity,
2080
        // we need to fetch it from the db anyway in order to merge.
2081
        // MANAGED entities are ignored by the merge operation.
2082
        $managedCopy = $entity;
2083
        if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) {
2084
            // Try to look the entity up in the identity map.
2085
            $id = $class->getIdentifierValues($entity);
2086
            // If there is no ID, it is actually NEW.
2087
            if (!$id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
2088
                $managedCopy = $this->newInstance($class);
2089
                $this->persistNew($class, $managedCopy);
2090
            } else {
2091
                $flatId      = ($class->containsForeignIdentifier())
2092
                    ? $this->identifierFlattener->flattenIdentifier($class, $id)
2093
                    : $id;
2094
                $managedCopy = $this->tryGetById($flatId, $class->getRootEntityName());
2095
                if ($managedCopy) {
2096
                    // We have the entity in-memory already, just make sure its not removed.
2097
                    if ($this->getEntityState($managedCopy) == self::STATE_REMOVED) {
2098
                        throw new \InvalidArgumentException('Removed entity cannot be merged');
2099
                    }
2100
                } else {
2101
                    // We need to fetch the managed copy in order to merge.
2102
                    $managedCopy = $this->manager->find($class->getName(), $flatId);
2103
                }
2104
                if ($managedCopy === null) {
2105
                    // If the identifier is ASSIGNED, it is NEW, otherwise an error
2106
                    // since the managed entity was not found.
2107
                    if (!$class->isIdentifierNatural()) {
2108
                        throw new \OutOfBoundsException('Entity not found');
2109
                    }
2110
                    $managedCopy = $this->newInstance($class);
2111
                    $class->setIdentifierValues($managedCopy, $id);
2112
                    $this->persistNew($class, $managedCopy);
2113
                }
2114
            }
2115
2116
            $visited[$oid] = $managedCopy; // mark visited
2117
            if ($this->isLoaded($entity)) {
2118
                if ($managedCopy instanceof Proxy && !$managedCopy->__isInitialized()) {
2119
                    $managedCopy->__load();
2120
                }
2121
                $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy);
2122
            }
2123
            if ($class->isChangeTrackingDeferredExplicit()) {
2124
                $this->scheduleForDirtyCheck($entity);
2125
            }
2126
        }
2127
        if ($prevManagedCopy !== null) {
2128
            $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, $managedCopy);
2129
        }
2130
        // Mark the managed copy visited as well
2131
        $visited[spl_object_hash($managedCopy)] = $managedCopy;
2132
        $this->cascadeMerge($entity, $managedCopy, $visited);
2133
2134
        return $managedCopy;
2135
    }
2136
2137
    /**
2138
     * Executes a detach operation on the given entity.
2139
     *
2140
     * @param object  $entity
2141
     * @param array   $visited
2142
     * @param boolean $noCascade if true, don't cascade detach operation.
2143
     *
2144
     * @return void
2145
     */
2146
    private function doDetach($entity, array &$visited, $noCascade = false)
2147
    {
2148
        $oid = spl_object_hash($entity);
2149
        if (isset($visited[$oid])) {
2150
            return; // Prevent infinite recursion
2151
        }
2152
        $visited[$oid] = $entity; // mark visited
2153
        switch ($this->getEntityState($entity, self::STATE_DETACHED)) {
2154
            case self::STATE_MANAGED:
2155
                if ($this->isInIdentityMap($entity)) {
2156
                    $this->removeFromIdentityMap($entity);
2157
                }
2158
                unset(
2159
                    $this->entityInsertions[$oid],
2160
                    $this->entityUpdates[$oid],
2161
                    $this->entityDeletions[$oid],
2162
                    $this->entityIdentifiers[$oid],
2163
                    $this->entityStates[$oid],
2164
                    $this->originalEntityData[$oid]
2165
                );
2166
                break;
2167
            case self::STATE_NEW:
2168
            case self::STATE_DETACHED:
2169
                return;
2170
        }
2171
        if (!$noCascade) {
2172
            $this->cascadeDetach($entity, $visited);
2173
        }
2174
    }
2175
2176
}
2177