Completed
Pull Request — master (#14)
by Pavel
03:32
created

UnitOfWork::commit()   F

Complexity

Conditions 23
Paths 644

Size

Total Lines 77
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 42
CRAP Score 34.1099

Importance

Changes 0
Metric Value
dl 0
loc 77
c 0
b 0
f 0
ccs 42
cts 58
cp 0.7241
rs 2.5974
cc 23
eloc 43
nc 644
nop 1
crap 34.1099

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
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 18
    public function __construct(EntityManager $manager)
104
    {
105 18
        $this->manager                    = $manager;
106 18
        $this->identifierFlattener        = new IdentifierFlattener($this->manager);
107 18
        $this->reflectionPropertiesGetter = new ReflectionPropertiesGetter(new RuntimeReflectionService());
108 18
    }
109
110
    /**
111
     * @param $className
112
     *
113
     * @return EntityPersister
114
     */
115 17
    public function getEntityPersister($className)
116
    {
117 17
        if (!array_key_exists($className, $this->persisters)) {
118
            /** @var ApiMetadata $classMetadata */
119 17
            $classMetadata = $this->manager->getClassMetadata($className);
120
121 17
            $api = $this->createApi($classMetadata);
122
123 17
            if ($api instanceof EntityCacheAwareInterface) {
124 17
                $api->setEntityCache($this->createEntityCache($classMetadata));
125 17
            }
126
127 17
            $this->persisters[$className] = new ApiPersister($this->manager, $api);
128 17
        }
129
130 17
        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 12
    public function getOrCreateEntity($className, \stdClass $data)
182
    {
183
        /** @var EntityMetadata $class */
184 12
        $class    = $this->manager->getClassMetadata($className);
185 12
        $hydrator = new EntityHydrator($this->manager, $class);
186
187 12
        $tmpEntity = $hydrator->hydarate($data);
188
189 12
        $id     = $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($tmpEntity));
190 12
        $idHash = implode(' ', $id);
191
192 12
        $overrideLocalValues = false;
193 12
        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 11
            $entity                                             = $this->newInstance($class);
209 11
            $oid                                                = spl_object_hash($entity);
210 11
            $this->entityIdentifiers[$oid]                      = $id;
211 11
            $this->entityStates[$oid]                           = self::STATE_MANAGED;
212 11
            $this->originalEntityData[$oid]                     = $data;
213 11
            $this->identityMap[$class->rootEntityName][$idHash] = $entity;
214 11
            if ($entity instanceof NotifyPropertyChanged) {
215
                $entity->addPropertyChangedListener($this);
216
            }
217 11
            $overrideLocalValues = true;
218
        }
219
220 12
        if (!$overrideLocalValues) {
221
            return $entity;
222
        }
223
224 12
        $entity = $hydrator->hydarate($data, $entity);
225
226 12
        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 3
    public function registerManaged($entity, array $id, \stdClass $data = null)
240
    {
241 3
        $oid = spl_object_hash($entity);
242
243 3
        $this->entityIdentifiers[$oid]  = $id;
244 3
        $this->entityStates[$oid]       = self::STATE_MANAGED;
245 3
        $this->originalEntityData[$oid] = $data;
246
247 3
        $this->addToIdentityMap($entity);
248
249 3
        if ($entity instanceof NotifyPropertyChanged && (!$entity instanceof Proxy || $entity->__isInitialized())) {
250
            $entity->addPropertyChangedListener($this);
251
        }
252 3
    }
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 7
    public function addToIdentityMap($entity)
269
    {
270
        /** @var EntityMetadata $classMetadata */
271 7
        $classMetadata = $this->manager->getClassMetadata(get_class($entity));
272 7
        $idHash        = implode(' ', $this->entityIdentifiers[spl_object_hash($entity)]);
273
274 7
        if ($idHash === '') {
275
            throw new \InvalidArgumentException('Entitty does not have valid identifiers to be stored at identity map');
276
        }
277
278 7
        $className = $classMetadata->rootEntityName;
279
280 7
        if (isset($this->identityMap[$className][$idHash])) {
281
            return false;
282
        }
283
284 7
        $this->identityMap[$className][$idHash] = $entity;
285
286 7
        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 4
    public function getEntityState($entity, $assume = null)
385
    {
386 4
        $oid = spl_object_hash($entity);
387 4
        if (isset($this->entityStates[$oid])) {
388 2
            return $this->entityStates[$oid];
389
        }
390 4
        if ($assume !== null) {
391 4
            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 11
    public function tryGetById($id, $rootClassName)
417
    {
418
        /** @var EntityMetadata $metadata */
419 11
        $metadata = $this->manager->getClassMetadata($rootClassName);
420 11
        $idHash   = implode(' ', (array)$this->identifierFlattener->flattenIdentifier($metadata, $id));
421
422 11
        if (isset($this->identityMap[$rootClassName][$idHash])) {
423 4
            return $this->identityMap[$rootClassName][$idHash];
424
        }
425
426 11
        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 4
    public function persist($entity)
462
    {
463 4
        $visited = [];
464 4
        $this->doPersist($entity, $visited);
465 4
    }
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 4
    public function scheduleForInsert($entity)
524
    {
525 4
        $oid = spl_object_hash($entity);
526 4
        if (isset($this->entityUpdates[$oid])) {
527
            throw new \InvalidArgumentException('Dirty entity cannot be scheduled for insertion');
528
        }
529 4
        if (isset($this->entityDeletions[$oid])) {
530
            throw new \InvalidArgumentException('Removed entity scheduled for insertion');
531
        }
532 4
        if (isset($this->originalEntityData[$oid]) && !isset($this->entityInsertions[$oid])) {
533
            throw new \InvalidArgumentException('Managed entity scheduled for insertion');
534
        }
535 4
        if (isset($this->entityInsertions[$oid])) {
536
            throw new \InvalidArgumentException('Entity scheduled for insertion twice');
537
        }
538 4
        $this->entityInsertions[$oid] = $entity;
539 4
        if (isset($this->entityIdentifiers[$oid])) {
540
            $this->addToIdentityMap($entity);
541
        }
542 4
        if ($entity instanceof NotifyPropertyChanged) {
543
            $entity->addPropertyChangedListener($this);
544
        }
545 4
    }
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 4
    public function commit($entity = null)
722
    {
723
        // Compute changes done since last commit.
724 4
        if ($entity === null) {
725 4
            $this->computeChangeSets();
726 4
        } 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 4
        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 4
        ) {
740 1
            return; // Nothing to do.
741
        }
742 4
        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 4
        $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 4
        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 4
            foreach ($commitOrder as $class) {
757 4
                $this->executeInserts($class);
758 4
            }
759 4
        }
760 4
        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 4
        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 4
        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 4
        }
774
        // Entity deletions come last and need to be in reverse commit order
775 4
        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 4
        foreach ($this->visitedCollections as $coll) {
783 2
            $coll->takeSnapshot();
784 4
        }
785
786
        // Clear up
787 4
        $this->entityInsertions =
788 4
        $this->entityUpdates =
789 4
        $this->entityDeletions =
790 4
        $this->extraUpdates =
791 4
        $this->entityChangeSets =
792 4
        $this->collectionUpdates =
793 4
        $this->collectionDeletions =
794 4
        $this->visitedCollections =
795 4
        $this->scheduledForSynchronization =
796 4
        $this->orphanRemovals = [];
797 4
    }
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 4
    public function computeChangeSet(ApiMetadata $class, $entity)
852
    {
853 4
        $oid = spl_object_hash($entity);
854 4
        if (isset($this->readOnlyObjects[$oid])) {
855
            return;
856
        }
857
        //        if ( ! $class->isInheritanceTypeNone()) {
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...
858
        //            $class = $this->em->getClassMetadata(get_class($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...
859
        //        }
860
        //        $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preFlush) & ~ListenersInvoker::INVOKE_MANAGER;
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...
861
        //        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...
862
        //            $this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($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...
863
        //        }
864 4
        $actualData = [];
865 4
        foreach ($class->getReflectionProperties() as $name => $refProp) {
866 4
            $value = $refProp->getValue($entity);
867 4
            if ($class->isCollectionValuedAssociation($name) && $value !== null) {
868 2
                if ($value instanceof ApiCollection) {
869 1
                    if ($value->getOwner() === $entity) {
870 1
                        continue;
871
                    }
872
                    $value = new ArrayCollection($value->getValues());
873
                }
874
                // If $value is not a Collection then use an ArrayCollection.
875 2
                if (!$value instanceof Collection) {
876
                    $value = new ArrayCollection($value);
877
                }
878 2
                $assoc = $class->getAssociationMapping($name);
879
                // Inject PersistentCollection
880 2
                $value = new ApiCollection(
881 2
                    $this->manager,
882 2
                    $this->manager->getClassMetadata($assoc['target']),
883
                    $value
884 2
                );
885 2
                $value->setOwner($entity, $assoc);
886 2
                $value->setDirty(!$value->isEmpty());
887 2
                $class->getReflectionProperty($name)->setValue($entity, $value);
888 2
                $actualData[$name] = $value;
889 2
                continue;
890
            }
891 4
            if (!$class->isIdentifier($name)) {
892 4
                $actualData[$name] = $value;
893 4
            }
894 4
        }
895 4
        if (!isset($this->originalEntityData[$oid])) {
896
            // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
897
            // These result in an INSERT.
898 4
            $this->originalEntityData[$oid] = $actualData;
899 4
            $changeSet                      = [];
900 4
            foreach ($actualData as $propName => $actualValue) {
901 4 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...
902 4
                    $changeSet[$propName] = [null, $actualValue];
903 4
                    continue;
904
                }
905 4
                $assoc = $class->getAssociationMapping($propName);
906 4
                if ($assoc['isOwningSide'] && $assoc['type'] & ApiMetadata::TO_ONE) {
907 4
                    $changeSet[$propName] = [null, $actualValue];
908 4
                }
909 4
            }
910 4
            $this->entityChangeSets[$oid] = $changeSet;
911 4
        } else {
912
            // Entity is "fully" MANAGED: it was already fully persisted before
913
            // and we have a copy of the original data
914 2
            $originalData           = $this->originalEntityData[$oid];
915 2
            $isChangeTrackingNotify = false;
916 2
            $changeSet              = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
917 2
                ? $this->entityChangeSets[$oid]
918 2
                : [];
919 2
            foreach ($actualData as $propName => $actualValue) {
920
                // skip field, its a partially omitted one!
921 2
                if (!(isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
922
                    continue;
923
                }
924 2
                $orgValue = $originalData[$propName];
925
                // skip if value haven't changed
926 2
                if ($orgValue === $actualValue) {
927 2
                    continue;
928
                }
929
                // if regular field
930 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...
931
                    if ($isChangeTrackingNotify) {
932
                        continue;
933
                    }
934
                    $changeSet[$propName] = [$orgValue, $actualValue];
935
                    continue;
936
                }
937 1
                $assoc = $class->getAssociationMapping($propName);
938
                // Persistent collection was exchanged with the "originally"
939
                // created one. This can only mean it was cloned and replaced
940
                // on another entity.
941 1
                if ($actualValue instanceof ApiCollection) {
942
                    $owner = $actualValue->getOwner();
943
                    if ($owner === null) { // cloned
944
                        $actualValue->setOwner($entity, $assoc);
945
                    } else {
946
                        if ($owner !== $entity) { // no clone, we have to fix
947
                            if (!$actualValue->isInitialized()) {
948
                                $actualValue->initialize(); // we have to do this otherwise the cols share state
949
                            }
950
                            $newValue = clone $actualValue;
951
                            $newValue->setOwner($entity, $assoc);
952
                            $class->getReflectionProperty($propName)->setValue($entity, $newValue);
953
                        }
954
                    }
955
                }
956 1
                if ($orgValue instanceof ApiCollection) {
957
                    // A PersistentCollection was de-referenced, so delete it.
958
                    $coid = spl_object_hash($orgValue);
959
                    if (isset($this->collectionDeletions[$coid])) {
960
                        continue;
961
                    }
962
                    $this->collectionDeletions[$coid] = $orgValue;
963
                    $changeSet[$propName]             = $orgValue; // Signal changeset, to-many assocs will be ignored.
964
                    continue;
965
                }
966 1
                if ($assoc['type'] & ApiMetadata::TO_ONE) {
967 1
                    if ($assoc['isOwningSide']) {
968 1
                        $changeSet[$propName] = [$orgValue, $actualValue];
969 1
                    }
970 1
                    if ($orgValue !== null && $assoc['orphanRemoval']) {
971
                        $this->scheduleOrphanRemoval($orgValue);
972
                    }
973 1
                }
974 2
            }
975 2
            if ($changeSet) {
976 1
                $this->entityChangeSets[$oid]   = $changeSet;
977 1
                $this->originalEntityData[$oid] = $actualData;
978 1
                $this->entityUpdates[$oid]      = $entity;
979 1
            }
980
        }
981
        // Look for changes in associations of the entity
982 4
        foreach ($class->getAssociationMappings() as $field => $assoc) {
983 4
            if (($val = $class->getReflectionProperty($field)->getValue($entity)) === null) {
984 4
                continue;
985
            }
986 2
            $this->computeAssociationChanges($assoc, $val);
987 2
            if (!isset($this->entityChangeSets[$oid]) &&
988 2
                $assoc['isOwningSide'] &&
989 2
                $assoc['type'] == ApiMetadata::MANY_TO_MANY &&
990 2
                $val instanceof ApiCollection &&
991
                $val->isDirty()
992 2
            ) {
993
                $this->entityChangeSets[$oid]   = [];
994
                $this->originalEntityData[$oid] = $actualData;
995
                $this->entityUpdates[$oid]      = $entity;
996
            }
997 4
        }
998 4
    }
999
1000
    /**
1001
     * Computes all the changes that have been done to entities and collections
1002
     * since the last commit and stores these changes in the _entityChangeSet map
1003
     * temporarily for access by the persisters, until the UoW commit is finished.
1004
     *
1005
     * @return void
1006
     */
1007 4
    public function computeChangeSets()
1008
    {
1009
        // Compute changes for INSERTed entities first. This must always happen.
1010 4
        $this->computeScheduleInsertsChangeSets();
1011
        // Compute changes for other MANAGED entities. Change tracking policies take effect here.
1012 4
        foreach ($this->identityMap as $className => $entities) {
1013 2
            $class = $this->manager->getClassMetadata($className);
1014
            // Skip class if instances are read-only
1015 2
            if ($class->isReadOnly()) {
1016
                continue;
1017
            }
1018
            // If change tracking is explicit or happens through notification, then only compute
1019
            // changes on entities of that type that are explicitly marked for synchronization.
1020 2
            switch (true) {
1021 2
                case ($class->isChangeTrackingDeferredImplicit()):
1022 2
                    $entitiesToProcess = $entities;
1023 2
                    break;
1024
                case (isset($this->scheduledForSynchronization[$className])):
1025
                    $entitiesToProcess = $this->scheduledForSynchronization[$className];
1026
                    break;
1027
                default:
1028
                    $entitiesToProcess = [];
1029
            }
1030 2
            foreach ($entitiesToProcess as $entity) {
1031
                // Ignore uninitialized proxy objects
1032 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...
1033
                    continue;
1034
                }
1035
                // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
1036 2
                $oid = spl_object_hash($entity);
1037 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...
1038 2
                    !isset($this->entityDeletions[$oid]) &&
1039 2
                    isset($this->entityStates[$oid])
1040 2
                ) {
1041 2
                    $this->computeChangeSet($class, $entity);
1042 2
                }
1043 2
            }
1044 4
        }
1045 4
    }
1046
1047
    /**
1048
     * INTERNAL:
1049
     * Schedules an orphaned entity for removal. The remove() operation will be
1050
     * invoked on that entity at the beginning of the next commit of this
1051
     * UnitOfWork.
1052
     *
1053
     * @ignore
1054
     *
1055
     * @param object $entity
1056
     *
1057
     * @return void
1058
     */
1059
    public function scheduleOrphanRemoval($entity)
1060
    {
1061
        $this->orphanRemovals[spl_object_hash($entity)] = $entity;
1062
    }
1063
1064 2
    public function loadCollection(ApiCollection $collection)
1065
    {
1066 2
        $assoc     = $collection->getMapping();
1067 2
        $persister = $this->getEntityPersister($assoc['target']);
1068 2
        switch ($assoc['type']) {
1069 2
            case ApiMetadata::ONE_TO_MANY:
1070 2
                $persister->loadOneToManyCollection($assoc, $collection->getOwner(), $collection);
1071 2
                break;
1072 2
        }
1073 2
        $collection->setInitialized(true);
1074 2
    }
1075
1076
    public function getCollectionPersister($association)
1077
    {
1078
        $role = isset($association['cache'])
1079
            ? $association['sourceEntity'] . '::' . $association['fieldName']
1080
            : $association['type'];
1081
        if (array_key_exists($role, $this->collectionPersisters)) {
1082
            return $this->collectionPersisters[$role];
1083
        }
1084
        $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...
1085
1086
        return $this->collectionPersisters[$role];
1087
    }
1088
1089
    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...
1090
    {
1091
    }
1092
1093 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...
1094
    {
1095 2
    }
1096
1097
    /**
1098
     * INTERNAL:
1099
     * Sets a property value of the original data array of an entity.
1100
     *
1101
     * @ignore
1102
     *
1103
     * @param string $oid
1104
     * @param string $property
1105
     * @param mixed  $value
1106
     *
1107
     * @return void
1108
     */
1109 9
    public function setOriginalEntityProperty($oid, $property, $value)
1110
    {
1111 9
        if (!array_key_exists($oid, $this->originalEntityData)) {
1112 9
            $this->originalEntityData[$oid] = new \stdClass();
1113 9
        }
1114
1115 9
        $this->originalEntityData[$oid]->$property = $value;
1116 9
    }
1117
1118
    public function scheduleExtraUpdate($entity, $changeset)
1119
    {
1120
        $oid         = spl_object_hash($entity);
1121
        $extraUpdate = [$entity, $changeset];
1122
        if (isset($this->extraUpdates[$oid])) {
1123
            list(, $changeset2) = $this->extraUpdates[$oid];
1124
            $extraUpdate = [$entity, $changeset + $changeset2];
1125
        }
1126
        $this->extraUpdates[$oid] = $extraUpdate;
1127
    }
1128
1129
    /**
1130
     * Refreshes the state of the given entity from the database, overwriting
1131
     * any local, unpersisted changes.
1132
     *
1133
     * @param object $entity The entity to refresh.
1134
     *
1135
     * @return void
1136
     *
1137
     * @throws InvalidArgumentException If the entity is not MANAGED.
1138
     */
1139
    public function refresh($entity)
1140
    {
1141
        $visited = [];
1142
        $this->doRefresh($entity, $visited);
1143
    }
1144
1145
    /**
1146
     * Clears the UnitOfWork.
1147
     *
1148
     * @param string|null $entityName if given, only entities of this type will get detached.
1149
     *
1150
     * @return void
1151
     */
1152
    public function clear($entityName = null)
1153
    {
1154
        if ($entityName === null) {
1155
            $this->identityMap =
1156
            $this->entityIdentifiers =
1157
            $this->originalEntityData =
1158
            $this->entityChangeSets =
1159
            $this->entityStates =
1160
            $this->scheduledForSynchronization =
1161
            $this->entityInsertions =
1162
            $this->entityUpdates =
1163
            $this->entityDeletions =
1164
            $this->collectionDeletions =
1165
            $this->collectionUpdates =
1166
            $this->extraUpdates =
1167
            $this->readOnlyObjects =
1168
            $this->visitedCollections =
1169
            $this->orphanRemovals = [];
1170
        } else {
1171
            $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...
1172
            $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...
1173
        }
1174
    }
1175
1176
    /**
1177
     * @param PersistentCollection $coll
1178
     *
1179
     * @return bool
1180
     */
1181
    public function isCollectionScheduledForDeletion(PersistentCollection $coll)
1182
    {
1183
        return isset($this->collectionDeletions[spl_object_hash($coll)]);
1184
    }
1185
1186
    /**
1187
     * Schedules an entity for dirty-checking at commit-time.
1188
     *
1189
     * @param object $entity The entity to schedule for dirty-checking.
1190
     *
1191
     * @return void
1192
     *
1193
     * @todo Rename: scheduleForSynchronization
1194
     */
1195
    public function scheduleForDirtyCheck($entity)
1196
    {
1197
        $rootClassName                                                               =
1198
            $this->manager->getClassMetadata(get_class($entity))->getRootEntityName();
1199
        $this->scheduledForSynchronization[$rootClassName][spl_object_hash($entity)] = $entity;
1200
    }
1201
1202
    /**
1203
     * Deletes an entity as part of the current unit of work.
1204
     *
1205
     * @param object $entity The entity to remove.
1206
     *
1207
     * @return void
1208
     */
1209
    public function remove($entity)
1210
    {
1211
        $visited = [];
1212
        $this->doRemove($entity, $visited);
1213
    }
1214
1215
    /**
1216
     * Merges the state of the given detached entity into this UnitOfWork.
1217
     *
1218
     * @param object $entity
1219
     *
1220
     * @return object The managed copy of the entity.
1221
     */
1222
    public function merge($entity)
1223
    {
1224
        $visited = [];
1225
1226
        return $this->doMerge($entity, $visited);
1227
    }
1228
1229
    /**
1230
     * Detaches an entity from the persistence management. It's persistence will
1231
     * no longer be managed by Doctrine.
1232
     *
1233
     * @param object $entity The entity to detach.
1234
     *
1235
     * @return void
1236
     */
1237
    public function detach($entity)
1238
    {
1239
        $visited = [];
1240
        $this->doDetach($entity, $visited);
1241
    }
1242
1243
    /**
1244
     * @param ApiMetadata $class
1245
     *
1246
     * @return \Doctrine\Common\Persistence\ObjectManagerAware|object
1247
     */
1248 11
    private function newInstance(ApiMetadata $class)
1249
    {
1250 11
        $entity = $class->newInstance();
1251
1252 11
        if ($entity instanceof ObjectManagerAware) {
1253
            $entity->injectObjectManager($this->manager, $class);
1254
        }
1255
1256 11
        return $entity;
1257
    }
1258
1259
    /**
1260
     * @param ApiMetadata $classMetadata
1261
     *
1262
     * @return EntityDataCacheInterface
1263
     */
1264 17
    private function createEntityCache(ApiMetadata $classMetadata)
1265
    {
1266 17
        $configuration = $this->manager->getConfiguration()->getCacheConfiguration($classMetadata->getName());
1267 17
        $cache         = new VoidEntityCache($classMetadata);
1268 17
        if ($configuration->isEnabled() && $this->manager->getConfiguration()->getApiCache()) {
1269
            $cache =
1270 1
                new LoggingCache(
1271 1
                    new ApiEntityCache(
1272 1
                        $this->manager->getConfiguration()->getApiCache(),
1273 1
                        $classMetadata,
1274
                        $configuration
1275 1
                    ),
1276 1
                    $this->manager->getConfiguration()->getApiCacheLogger()
1277 1
                );
1278
1279 1
            return $cache;
1280
        }
1281
1282 16
        return $cache;
1283
    }
1284
1285
    /**
1286
     * @param ApiMetadata $classMetadata
1287
     *
1288
     * @return CrudsApiInterface
1289
     */
1290 17
    private function createApi(ApiMetadata $classMetadata)
1291
    {
1292 17
        $client = $this->manager->getConfiguration()->getRegistry()->get($classMetadata->getClientName());
1293
1294 17
        $api = $this->manager
1295 17
            ->getConfiguration()
1296 17
            ->getResolver()
1297 17
            ->resolve($classMetadata->getApiName())
1298 17
            ->createApi(
1299 17
                $client,
1300
                $classMetadata
1301 17
            );
1302
1303 17
        return $api;
1304
    }
1305
1306 4
    private function doPersist($entity, $visited)
1307
    {
1308 4
        $oid = spl_object_hash($entity);
1309 4
        if (isset($visited[$oid])) {
1310
            return; // Prevent infinite recursion
1311
        }
1312 4
        $visited[$oid] = $entity; // Mark visited
1313 4
        $class         = $this->manager->getClassMetadata(get_class($entity));
1314
        // We assume NEW, so DETACHED entities result in an exception on flush (constraint violation).
1315
        // If we would detect DETACHED here we would throw an exception anyway with the same
1316
        // consequences (not recoverable/programming error), so just assuming NEW here
1317
        // lets us avoid some database lookups for entities with natural identifiers.
1318 4
        $entityState = $this->getEntityState($entity, self::STATE_NEW);
1319
        switch ($entityState) {
1320 4
            case self::STATE_MANAGED:
1321
                $this->scheduleForDirtyCheck($entity);
1322
                break;
1323 4
            case self::STATE_NEW:
1324 4
                $this->persistNew($class, $entity);
1325 4
                break;
1326
            case self::STATE_REMOVED:
1327
                // Entity becomes managed again
1328
                unset($this->entityDeletions[$oid]);
1329
                $this->addToIdentityMap($entity);
1330
                $this->entityStates[$oid] = self::STATE_MANAGED;
1331
                break;
1332
            case self::STATE_DETACHED:
1333
                // Can actually not happen right now since we assume STATE_NEW.
1334
                throw new \InvalidArgumentException('Detached entity cannot be persisted');
1335
            default:
1336
                throw new \UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
1337
        }
1338 4
        $this->cascadePersist($entity, $visited);
1339 4
    }
1340
1341
    /**
1342
     * Cascades the save operation to associated entities.
1343
     *
1344
     * @param object $entity
1345
     * @param array  $visited
1346
     *
1347
     * @return void
1348
     * @throws \InvalidArgumentException
1349
     * @throws MappingException
1350
     */
1351 4
    private function cascadePersist($entity, array &$visited)
1352
    {
1353 4
        $class               = $this->manager->getClassMetadata(get_class($entity));
1354 4
        $associationMappings = [];
1355 4
        foreach ($class->getAssociationNames() as $name) {
1356 4
            $assoc = $class->getAssociationMapping($name);
1357 4
            if ($assoc['isCascadePersist']) {
1358
                $associationMappings[$name] = $assoc;
1359
            }
1360 4
        }
1361 4
        foreach ($associationMappings as $assoc) {
1362
            $relatedEntities = $class->getReflectionProperty($assoc['field'])->getValue($entity);
1363
            switch (true) {
1364
                case ($relatedEntities instanceof ApiCollection):
1365
                    // Unwrap so that foreach() does not initialize
1366
                    $relatedEntities = $relatedEntities->unwrap();
1367
                // break; is commented intentionally!
1368
                case ($relatedEntities instanceof Collection):
1369
                case (is_array($relatedEntities)):
1370
                    if (($assoc['type'] & ApiMetadata::TO_MANY) <= 0) {
1371
                        throw new \InvalidArgumentException('Invalid association for cascade');
1372
                    }
1373
                    foreach ($relatedEntities as $relatedEntity) {
1374
                        $this->doPersist($relatedEntity, $visited);
1375
                    }
1376
                    break;
1377
                case ($relatedEntities !== null):
1378
                    if (!$relatedEntities instanceof $assoc['target']) {
1379
                        throw new \InvalidArgumentException('Invalid association for cascade');
1380
                    }
1381
                    $this->doPersist($relatedEntities, $visited);
1382
                    break;
1383
                default:
1384
                    // Do nothing
1385
            }
1386 4
        }
1387 4
    }
1388
1389
    /**
1390
     * @param ApiMetadata $class
1391
     * @param object      $entity
1392
     *
1393
     * @return void
1394
     */
1395 4
    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...
1396
    {
1397 4
        $oid = spl_object_hash($entity);
1398
        //        $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...
1399
        //        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...
1400
        //            $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...
1401
        //        }
1402
        //        $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...
1403
        //        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...
1404
        //            $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...
1405
        //            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...
1406
        //                $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...
1407
        //                $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...
1408
        //            }
1409
        //            $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...
1410
        //        }
1411 4
        $this->entityStates[$oid] = self::STATE_MANAGED;
1412 4
        $this->scheduleForInsert($entity);
1413 4
    }
1414
1415
    /**
1416
     * Gets the commit order.
1417
     *
1418
     * @param array|null $entityChangeSet
1419
     *
1420
     * @return array
1421
     */
1422 4
    private function getCommitOrder(array $entityChangeSet = null)
1423
    {
1424 4
        if ($entityChangeSet === null) {
1425 4
            $entityChangeSet = array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions);
1426 4
        }
1427 4
        $calc = $this->getCommitOrderCalculator();
1428
        // See if there are any new classes in the changeset, that are not in the
1429
        // commit order graph yet (don't have a node).
1430
        // We have to inspect changeSet to be able to correctly build dependencies.
1431
        // It is not possible to use IdentityMap here because post inserted ids
1432
        // are not yet available.
1433
        /** @var ApiMetadata[] $newNodes */
1434 4
        $newNodes = [];
1435 4
        foreach ((array)$entityChangeSet as $entity) {
1436 4
            $class = $this->manager->getClassMetadata(get_class($entity));
1437 4
            if ($calc->hasNode($class->getName())) {
1438
                continue;
1439
            }
1440 4
            $calc->addNode($class->getName(), $class);
1441 4
            $newNodes[] = $class;
1442 4
        }
1443
        // Calculate dependencies for new nodes
1444 4
        while ($class = array_pop($newNodes)) {
1445 4
            foreach ($class->getAssociationMappings() as $assoc) {
1446 4
                if (!($assoc['isOwningSide'] && $assoc['type'] & ApiMetadata::TO_ONE)) {
1447 4
                    continue;
1448
                }
1449 4
                $targetClass = $this->manager->getClassMetadata($assoc['target']);
1450 4
                if (!$calc->hasNode($targetClass->getName())) {
1451 2
                    $calc->addNode($targetClass->getName(), $targetClass);
1452 2
                    $newNodes[] = $targetClass;
1453 2
                }
1454 4
                $calc->addDependency($targetClass->getName(), $class->name, (int)empty($assoc['nullable']));
1455
                // If the target class has mapped subclasses, these share the same dependency.
1456 4
                if (!$targetClass->getSubclasses()) {
1457 4
                    continue;
1458
                }
1459
                foreach ($targetClass->getSubclasses() as $subClassName) {
1460
                    $targetSubClass = $this->manager->getClassMetadata($subClassName);
1461
                    if (!$calc->hasNode($subClassName)) {
1462
                        $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...
1463
                        $newNodes[] = $targetSubClass;
1464
                    }
1465
                    $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...
1466
                }
1467 4
            }
1468 4
        }
1469
1470 4
        return $calc->sort();
1471
    }
1472
1473
    /**
1474
     * Helper method to show an object as string.
1475
     *
1476
     * @param object $obj
1477
     *
1478
     * @return string
1479
     */
1480
    private static function objToStr($obj)
1481
    {
1482
        return method_exists($obj, '__toString') ? (string)$obj : get_class($obj) . '@' . spl_object_hash($obj);
1483
    }
1484
1485 4
    private function getCommitOrderCalculator()
1486
    {
1487 4
        return new Utility\CommitOrderCalculator();
1488
    }
1489
1490
    /**
1491
     * Only flushes the given entity according to a ruleset that keeps the UoW consistent.
1492
     *
1493
     * 1. All entities scheduled for insertion, (orphan) removals and changes in collections are processed as well!
1494
     * 2. Read Only entities are skipped.
1495
     * 3. Proxies are skipped.
1496
     * 4. Only if entity is properly managed.
1497
     *
1498
     * @param object $entity
1499
     *
1500
     * @return void
1501
     *
1502
     * @throws \InvalidArgumentException
1503
     */
1504
    private function computeSingleEntityChangeSet($entity)
1505
    {
1506
        $state = $this->getEntityState($entity);
1507
        if ($state !== self::STATE_MANAGED && $state !== self::STATE_REMOVED) {
1508
            throw new \InvalidArgumentException(
1509
                "Entity has to be managed or scheduled for removal for single computation " . self::objToStr($entity)
1510
            );
1511
        }
1512
        $class = $this->manager->getClassMetadata(get_class($entity));
1513
        // Compute changes for INSERTed entities first. This must always happen even in this case.
1514
        $this->computeScheduleInsertsChangeSets();
1515
        if ($class->isReadOnly()) {
1516
            return;
1517
        }
1518
        // Ignore uninitialized proxy objects
1519
        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...
1520
            return;
1521
        }
1522
        // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
1523
        $oid = spl_object_hash($entity);
1524 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...
1525
            !isset($this->entityDeletions[$oid]) &&
1526
            isset($this->entityStates[$oid])
1527
        ) {
1528
            $this->computeChangeSet($class, $entity);
1529
        }
1530
    }
1531
1532
    /**
1533
     * Computes the changesets of all entities scheduled for insertion.
1534
     *
1535
     * @return void
1536
     */
1537 4
    private function computeScheduleInsertsChangeSets()
1538
    {
1539 4
        foreach ($this->entityInsertions as $entity) {
1540 4
            $class = $this->manager->getClassMetadata(get_class($entity));
1541 4
            $this->computeChangeSet($class, $entity);
1542 4
        }
1543 4
    }
1544
1545
    /**
1546
     * Computes the changes of an association.
1547
     *
1548
     * @param array $assoc The association mapping.
1549
     * @param mixed $value The value of the association.
1550
     *
1551
     * @throws \InvalidArgumentException
1552
     * @throws \UnexpectedValueException
1553
     *
1554
     * @return void
1555
     */
1556 2
    private function computeAssociationChanges($assoc, $value)
1557
    {
1558 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...
1559
            return;
1560
        }
1561 2
        if ($value instanceof ApiCollection && $value->isDirty()) {
1562 2
            $coid                            = spl_object_hash($value);
1563 2
            $this->collectionUpdates[$coid]  = $value;
1564 2
            $this->visitedCollections[$coid] = $value;
1565 2
        }
1566
        // Look through the entities, and in any of their associations,
1567
        // 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...
1568
        // Unwrap. Uninitialized collections will simply be empty.
1569 2
        $unwrappedValue  = ($assoc['type'] & ApiMetadata::TO_ONE) ? [$value] : $value->unwrap();
1570 2
        $targetClass     = $this->manager->getClassMetadata($assoc['target']);
1571 2
        $targetClassName = $targetClass->getName();
1572 2
        foreach ($unwrappedValue as $key => $entry) {
1573 2
            if (!($entry instanceof $targetClassName)) {
1574
                throw new \InvalidArgumentException('Invalid association');
1575
            }
1576 2
            $state = $this->getEntityState($entry, self::STATE_NEW);
1577 2
            if (!($entry instanceof $assoc['target'])) {
1578
                throw new \UnexpectedValueException('Unexpected association');
1579
            }
1580
            switch ($state) {
1581 2
                case self::STATE_NEW:
1582
                    if (!$assoc['isCascadePersist']) {
1583
                        throw new \InvalidArgumentException('New entity through relationship');
1584
                    }
1585
                    $this->persistNew($targetClass, $entry);
1586
                    $this->computeChangeSet($targetClass, $entry);
1587
                    break;
1588 2
                case self::STATE_REMOVED:
1589
                    // Consume the $value as array (it's either an array or an ArrayAccess)
1590
                    // and remove the element from Collection.
1591
                    if ($assoc['type'] & ApiMetadata::TO_MANY) {
1592
                        unset($value[$key]);
1593
                    }
1594
                    break;
1595 2
                case self::STATE_DETACHED:
1596
                    // Can actually not happen right now as we assume STATE_NEW,
1597
                    // so the exception will be raised from the DBAL layer (constraint violation).
1598
                    throw new \InvalidArgumentException('Detached entity through relationship');
1599
                    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...
1600 2
                default:
1601
                    // MANAGED associated entities are already taken into account
1602
                    // during changeset calculation anyway, since they are in the identity map.
1603 2
            }
1604 2
        }
1605 2
    }
1606
1607 4
    private function executeInserts(ApiMetadata $class)
1608
    {
1609 4
        $className = $class->getName();
1610 4
        $persister = $this->getEntityPersister($className);
1611 4
        foreach ($this->entityInsertions as $oid => $entity) {
1612 4
            if ($this->manager->getClassMetadata(get_class($entity))->getName() !== $className) {
1613 4
                continue;
1614
            }
1615 4
            $persister->pushNewEntity($entity);
1616 4
            unset($this->entityInsertions[$oid]);
1617 4
        }
1618 4
        $postInsertIds = $persister->flushNewEntities();
1619 4
        if ($postInsertIds) {
1620
            // Persister returned post-insert IDs
1621 4
            foreach ($postInsertIds as $postInsertId) {
1622 4
                $id      = $postInsertId['generatedId'];
1623 4
                $entity  = $postInsertId['entity'];
1624 4
                $oid     = spl_object_hash($entity);
1625 4
                $idField = $class->getIdentifierFieldNames()[0];
1626 4
                $class->getReflectionProperty($idField)->setValue($entity, $id);
1627 4
                $this->entityIdentifiers[$oid]            = [$idField => $id];
1628 4
                $this->entityStates[$oid]                 = self::STATE_MANAGED;
1629 4
                $this->originalEntityData[$oid][$idField] = $id;
1630 4
                $this->addToIdentityMap($entity);
1631 4
            }
1632 4
        }
1633 4
    }
1634
1635 1
    private function executeUpdates($class)
1636
    {
1637 1
        $className = $class->name;
1638 1
        $persister = $this->getEntityPersister($className);
1639 1
        foreach ($this->entityUpdates as $oid => $entity) {
1640 1
            if ($this->manager->getClassMetadata(get_class($entity))->getName() !== $className) {
1641 1
                continue;
1642
            }
1643 1
            $this->recomputeSingleEntityChangeSet($class, $entity);
1644
1645 1
            if (!empty($this->entityChangeSets[$oid])) {
1646 1
                $persister->update($entity);
1647 1
            }
1648 1
            unset($this->entityUpdates[$oid]);
1649 1
        }
1650 1
    }
1651
1652
    /**
1653
     * Executes a refresh operation on an entity.
1654
     *
1655
     * @param object $entity  The entity to refresh.
1656
     * @param array  $visited The already visited entities during cascades.
1657
     *
1658
     * @return void
1659
     *
1660
     * @throws \InvalidArgumentException If the entity is not MANAGED.
1661
     */
1662
    private function doRefresh($entity, array &$visited)
1663
    {
1664
        $oid = spl_object_hash($entity);
1665
        if (isset($visited[$oid])) {
1666
            return; // Prevent infinite recursion
1667
        }
1668
        $visited[$oid] = $entity; // mark visited
1669
        $class         = $this->manager->getClassMetadata(get_class($entity));
1670
        if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
1671
            throw new \InvalidArgumentException('Entity not managed');
1672
        }
1673
        $this->getEntityPersister($class->getName())->refresh(
1674
            array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
1675
            $entity
1676
        );
1677
        $this->cascadeRefresh($entity, $visited);
1678
    }
1679
1680
    /**
1681
     * Cascades a refresh operation to associated entities.
1682
     *
1683
     * @param object $entity
1684
     * @param array  $visited
1685
     *
1686
     * @return void
1687
     */
1688 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...
1689
    {
1690
        $class               = $this->manager->getClassMetadata(get_class($entity));
1691
        $associationMappings = array_filter(
1692
            $class->getAssociationMappings(),
1693
            function ($assoc) {
1694
                return $assoc['isCascadeRefresh'];
1695
            }
1696
        );
1697
        foreach ($associationMappings as $assoc) {
1698
            $relatedEntities = $class->getReflectionProperty($assoc['fieldName'])->getValue($entity);
1699
            switch (true) {
1700
                case ($relatedEntities instanceof ApiCollection):
1701
                    // Unwrap so that foreach() does not initialize
1702
                    $relatedEntities = $relatedEntities->unwrap();
1703
                // break; is commented intentionally!
1704
                case ($relatedEntities instanceof Collection):
1705
                case (is_array($relatedEntities)):
1706
                    foreach ($relatedEntities as $relatedEntity) {
1707
                        $this->doRefresh($relatedEntity, $visited);
1708
                    }
1709
                    break;
1710
                case ($relatedEntities !== null):
1711
                    $this->doRefresh($relatedEntities, $visited);
1712
                    break;
1713
                default:
1714
                    // Do nothing
1715
            }
1716
        }
1717
    }
1718
1719
    /**
1720
     * Cascades a detach operation to associated entities.
1721
     *
1722
     * @param object $entity
1723
     * @param array  $visited
1724
     *
1725
     * @return void
1726
     */
1727 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...
1728
    {
1729
        $class               = $this->manager->getClassMetadata(get_class($entity));
1730
        $associationMappings = array_filter(
1731
            $class->getAssociationMappings(),
1732
            function ($assoc) {
1733
                return $assoc['isCascadeDetach'];
1734
            }
1735
        );
1736
        foreach ($associationMappings as $assoc) {
1737
            $relatedEntities = $class->getReflectionProperty($assoc['fieldName'])->getValue($entity);
1738
            switch (true) {
1739
                case ($relatedEntities instanceof ApiCollection):
1740
                    // Unwrap so that foreach() does not initialize
1741
                    $relatedEntities = $relatedEntities->unwrap();
1742
                // break; is commented intentionally!
1743
                case ($relatedEntities instanceof Collection):
1744
                case (is_array($relatedEntities)):
1745
                    foreach ($relatedEntities as $relatedEntity) {
1746
                        $this->doDetach($relatedEntity, $visited);
1747
                    }
1748
                    break;
1749
                case ($relatedEntities !== null):
1750
                    $this->doDetach($relatedEntities, $visited);
1751
                    break;
1752
                default:
1753
                    // Do nothing
1754
            }
1755
        }
1756
    }
1757
1758
    /**
1759
     * Cascades a merge operation to associated entities.
1760
     *
1761
     * @param object $entity
1762
     * @param object $managedCopy
1763
     * @param array  $visited
1764
     *
1765
     * @return void
1766
     */
1767
    private function cascadeMerge($entity, $managedCopy, array &$visited)
1768
    {
1769
        $class               = $this->manager->getClassMetadata(get_class($entity));
1770
        $associationMappings = array_filter(
1771
            $class->getAssociationMappings(),
1772
            function ($assoc) {
1773
                return $assoc['isCascadeMerge'];
1774
            }
1775
        );
1776
        foreach ($associationMappings as $assoc) {
1777
            $relatedEntities = $class->getReflectionProperty($assoc['field'])->getValue($entity);
1778
            if ($relatedEntities instanceof Collection) {
1779
                if ($relatedEntities === $class->getReflectionProperty($assoc['field'])->getValue($managedCopy)) {
1780
                    continue;
1781
                }
1782
                if ($relatedEntities instanceof ApiCollection) {
1783
                    // Unwrap so that foreach() does not initialize
1784
                    $relatedEntities = $relatedEntities->unwrap();
1785
                }
1786
                foreach ($relatedEntities as $relatedEntity) {
1787
                    $this->doMerge($relatedEntity, $visited, $managedCopy, $assoc);
1788
                }
1789
            } else {
1790
                if ($relatedEntities !== null) {
1791
                    $this->doMerge($relatedEntities, $visited, $managedCopy, $assoc);
1792
                }
1793
            }
1794
        }
1795
    }
1796
1797
    /**
1798
     * Cascades the delete operation to associated entities.
1799
     *
1800
     * @param object $entity
1801
     * @param array  $visited
1802
     *
1803
     * @return void
1804
     */
1805
    private function cascadeRemove($entity, array &$visited)
1806
    {
1807
        $class               = $this->manager->getClassMetadata(get_class($entity));
1808
        $associationMappings = array_filter(
1809
            $class->getAssociationMappings(),
1810
            function ($assoc) {
1811
                return $assoc['isCascadeRemove'];
1812
            }
1813
        );
1814
        $entitiesToCascade   = [];
1815
        foreach ($associationMappings as $assoc) {
1816
            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...
1817
                $entity->__load();
1818
            }
1819
            $relatedEntities = $class->getReflectionProperty($assoc['fieldName'])->getValue($entity);
1820
            switch (true) {
1821
                case ($relatedEntities instanceof Collection):
1822
                case (is_array($relatedEntities)):
1823
                    // If its a PersistentCollection initialization is intended! No unwrap!
1824
                    foreach ($relatedEntities as $relatedEntity) {
1825
                        $entitiesToCascade[] = $relatedEntity;
1826
                    }
1827
                    break;
1828
                case ($relatedEntities !== null):
1829
                    $entitiesToCascade[] = $relatedEntities;
1830
                    break;
1831
                default:
1832
                    // Do nothing
1833
            }
1834
        }
1835
        foreach ($entitiesToCascade as $relatedEntity) {
1836
            $this->doRemove($relatedEntity, $visited);
1837
        }
1838
    }
1839
1840
    /**
1841
     * Executes any extra updates that have been scheduled.
1842
     */
1843
    private function executeExtraUpdates()
1844
    {
1845
        foreach ($this->extraUpdates as $oid => $update) {
1846
            list ($entity, $changeset) = $update;
1847
            $this->entityChangeSets[$oid] = $changeset;
1848
            $this->getEntityPersister(get_class($entity))->update($entity);
1849
        }
1850
        $this->extraUpdates = [];
1851
    }
1852
1853
    private function executeDeletions(ApiMetadata $class)
1854
    {
1855
        $className = $class->getName();
1856
        $persister = $this->getEntityPersister($className);
1857
        foreach ($this->entityDeletions as $oid => $entity) {
1858
            if ($this->manager->getClassMetadata(get_class($entity))->getName() !== $className) {
1859
                continue;
1860
            }
1861
            $persister->delete($entity);
1862
            unset(
1863
                $this->entityDeletions[$oid],
1864
                $this->entityIdentifiers[$oid],
1865
                $this->originalEntityData[$oid],
1866
                $this->entityStates[$oid]
1867
            );
1868
            // Entity with this $oid after deletion treated as NEW, even if the $oid
1869
            // is obtained by a new entity because the old one went out of scope.
1870
            //$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...
1871
            //            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...
1872
            //                $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...
1873
            //            }
1874
        }
1875
    }
1876
1877
    /**
1878
     * @param object $entity
1879
     * @param object $managedCopy
1880
     */
1881
    private function mergeEntityStateIntoManagedCopy($entity, $managedCopy)
1882
    {
1883
        $class = $this->manager->getClassMetadata(get_class($entity));
1884
        foreach ($this->reflectionPropertiesGetter->getProperties($class->getName()) as $prop) {
1885
            $name = $prop->name;
1886
            $prop->setAccessible(true);
1887
            if ($class->hasAssociation($name)) {
1888
                if (!$class->isIdentifier($name)) {
1889
                    $prop->setValue($managedCopy, $prop->getValue($entity));
1890
                }
1891
            } else {
1892
                $assoc2 = $class->getAssociationMapping($name);
1893
                if ($assoc2['type'] & ApiMetadata::TO_ONE) {
1894
                    $other = $prop->getValue($entity);
1895
                    if ($other === null) {
1896
                        $prop->setValue($managedCopy, null);
1897
                    } else {
1898
                        if ($other instanceof Proxy && !$other->__isInitialized()) {
1899
                            // do not merge fields marked lazy that have not been fetched.
1900
                            continue;
1901
                        }
1902
                        if (!$assoc2['isCascadeMerge']) {
1903
                            if ($this->getEntityState($other) === self::STATE_DETACHED) {
1904
                                $targetClass = $this->manager->getClassMetadata($assoc2['targetEntity']);
1905
                                $relatedId   = $targetClass->getIdentifierValues($other);
1906
                                if ($targetClass->getSubclasses()) {
1907
                                    $other = $this->manager->find($targetClass->getName(), $relatedId);
1908
                                } else {
1909
                                    $other = $this->manager->getProxyFactory()->getProxy(
1910
                                        $assoc2['targetEntity'],
1911
                                        $relatedId
1912
                                    );
1913
                                    $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...
1914
                                }
1915
                            }
1916
                            $prop->setValue($managedCopy, $other);
1917
                        }
1918
                    }
1919
                } else {
1920
                    $mergeCol = $prop->getValue($entity);
1921
                    if ($mergeCol instanceof ApiCollection && !$mergeCol->isInitialized()) {
1922
                        // do not merge fields marked lazy that have not been fetched.
1923
                        // keep the lazy persistent collection of the managed copy.
1924
                        continue;
1925
                    }
1926
                    $managedCol = $prop->getValue($managedCopy);
1927
                    if (!$managedCol) {
1928
                        $managedCol = new ApiCollection(
1929
                            $this->manager,
1930
                            $this->manager->getClassMetadata($assoc2['target']),
1931
                            new ArrayCollection
1932
                        );
1933
                        $managedCol->setOwner($managedCopy, $assoc2);
1934
                        $prop->setValue($managedCopy, $managedCol);
1935
                    }
1936
                    if ($assoc2['isCascadeMerge']) {
1937
                        $managedCol->initialize();
1938
                        // clear and set dirty a managed collection if its not also the same collection to merge from.
1939
                        if (!$managedCol->isEmpty() && $managedCol !== $mergeCol) {
1940
                            $managedCol->unwrap()->clear();
1941
                            $managedCol->setDirty(true);
1942
                            if ($assoc2['isOwningSide']
1943
                                && $assoc2['type'] == ApiMetadata::MANY_TO_MANY
1944
                                && $class->isChangeTrackingNotify()
1945
                            ) {
1946
                                $this->scheduleForDirtyCheck($managedCopy);
1947
                            }
1948
                        }
1949
                    }
1950
                }
1951
            }
1952
            if ($class->isChangeTrackingNotify()) {
1953
                // Just treat all properties as changed, there is no other choice.
1954
                $this->propertyChanged($managedCopy, $name, null, $prop->getValue($managedCopy));
1955
            }
1956
        }
1957
    }
1958
1959
    /**
1960
     * Deletes an entity as part of the current unit of work.
1961
     *
1962
     * This method is internally called during delete() cascades as it tracks
1963
     * the already visited entities to prevent infinite recursions.
1964
     *
1965
     * @param object $entity  The entity to delete.
1966
     * @param array  $visited The map of the already visited entities.
1967
     *
1968
     * @return void
1969
     *
1970
     * @throws \InvalidArgumentException If the instance is a detached entity.
1971
     * @throws \UnexpectedValueException
1972
     */
1973
    private function doRemove($entity, array &$visited)
1974
    {
1975
        $oid = spl_object_hash($entity);
1976
        if (isset($visited[$oid])) {
1977
            return; // Prevent infinite recursion
1978
        }
1979
        $visited[$oid] = $entity; // mark visited
1980
        // Cascade first, because scheduleForDelete() removes the entity from the identity map, which
1981
        // can cause problems when a lazy proxy has to be initialized for the cascade operation.
1982
        $this->cascadeRemove($entity, $visited);
1983
        $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...
1984
        $entityState = $this->getEntityState($entity);
1985
        switch ($entityState) {
1986
            case self::STATE_NEW:
1987
            case self::STATE_REMOVED:
1988
                // nothing to do
1989
                break;
1990
            case self::STATE_MANAGED:
1991
                $this->scheduleForDelete($entity);
1992
                break;
1993
            case self::STATE_DETACHED:
1994
                throw new \InvalidArgumentException('Detached entity cannot be removed');
1995
            default:
1996
                throw new \UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
1997
        }
1998
    }
1999
2000
    /**
2001
     * Tests if an entity is loaded - must either be a loaded proxy or not a proxy
2002
     *
2003
     * @param object $entity
2004
     *
2005
     * @return bool
2006
     */
2007
    private function isLoaded($entity)
2008
    {
2009
        return !($entity instanceof Proxy) || $entity->__isInitialized();
2010
    }
2011
2012
    /**
2013
     * Sets/adds associated managed copies into the previous entity's association field
2014
     *
2015
     * @param object $entity
2016
     * @param array  $association
2017
     * @param object $previousManagedCopy
2018
     * @param object $managedCopy
2019
     *
2020
     * @return void
2021
     */
2022
    private function updateAssociationWithMergedEntity($entity, array $association, $previousManagedCopy, $managedCopy)
2023
    {
2024
        $assocField = $association['fieldName'];
2025
        $prevClass  = $this->manager->getClassMetadata(get_class($previousManagedCopy));
2026
        if ($association['type'] & ApiMetadata::TO_ONE) {
2027
            $prevClass->getReflectionProperty($assocField)->setValue($previousManagedCopy, $managedCopy);
2028
2029
            return;
2030
        }
2031
        /** @var array $value */
2032
        $value   = $prevClass->getReflectionProperty($assocField)->getValue($previousManagedCopy);
2033
        $value[] = $managedCopy;
2034
        if ($association['type'] == ApiMetadata::ONE_TO_MANY) {
2035
            $class = $this->manager->getClassMetadata(get_class($entity));
2036
            $class->getReflectionProperty($association['mappedBy'])->setValue($managedCopy, $previousManagedCopy);
2037
        }
2038
    }
2039
2040
    /**
2041
     * Executes a merge operation on an entity.
2042
     *
2043
     * @param object      $entity
2044
     * @param array       $visited
2045
     * @param object|null $prevManagedCopy
2046
     * @param array|null  $assoc
2047
     *
2048
     * @return object The managed copy of the entity.
2049
     *
2050
     * @throws \InvalidArgumentException If the entity instance is NEW.
2051
     * @throws \OutOfBoundsException
2052
     */
2053
    private function doMerge($entity, array &$visited, $prevManagedCopy = null, array $assoc = [])
2054
    {
2055
        $oid = spl_object_hash($entity);
2056
        if (isset($visited[$oid])) {
2057
            $managedCopy = $visited[$oid];
2058
            if ($prevManagedCopy !== null) {
2059
                $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, $managedCopy);
2060
            }
2061
2062
            return $managedCopy;
2063
        }
2064
        $class = $this->manager->getClassMetadata(get_class($entity));
2065
        // First we assume DETACHED, although it can still be NEW but we can avoid
2066
        // an extra db-roundtrip this way. If it is not MANAGED but has an identity,
2067
        // we need to fetch it from the db anyway in order to merge.
2068
        // MANAGED entities are ignored by the merge operation.
2069
        $managedCopy = $entity;
2070
        if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) {
2071
            // Try to look the entity up in the identity map.
2072
            $id = $class->getIdentifierValues($entity);
2073
            // If there is no ID, it is actually NEW.
2074
            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...
2075
                $managedCopy = $this->newInstance($class);
2076
                $this->persistNew($class, $managedCopy);
2077
            } else {
2078
                $flatId      = ($class->containsForeignIdentifier())
2079
                    ? $this->identifierFlattener->flattenIdentifier($class, $id)
2080
                    : $id;
2081
                $managedCopy = $this->tryGetById($flatId, $class->getRootEntityName());
2082
                if ($managedCopy) {
2083
                    // We have the entity in-memory already, just make sure its not removed.
2084
                    if ($this->getEntityState($managedCopy) == self::STATE_REMOVED) {
2085
                        throw new \InvalidArgumentException('Removed entity cannot be merged');
2086
                    }
2087
                } else {
2088
                    // We need to fetch the managed copy in order to merge.
2089
                    $managedCopy = $this->manager->find($class->getName(), $flatId);
2090
                }
2091
                if ($managedCopy === null) {
2092
                    // If the identifier is ASSIGNED, it is NEW, otherwise an error
2093
                    // since the managed entity was not found.
2094
                    if (!$class->isIdentifierNatural()) {
2095
                        throw new \OutOfBoundsException('Entity not found');
2096
                    }
2097
                    $managedCopy = $this->newInstance($class);
2098
                    $class->setIdentifierValues($managedCopy, $id);
2099
                    $this->persistNew($class, $managedCopy);
2100
                }
2101
            }
2102
2103
            $visited[$oid] = $managedCopy; // mark visited
2104
            if ($this->isLoaded($entity)) {
2105
                if ($managedCopy instanceof Proxy && !$managedCopy->__isInitialized()) {
2106
                    $managedCopy->__load();
2107
                }
2108
                $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy);
2109
            }
2110
            if ($class->isChangeTrackingDeferredExplicit()) {
2111
                $this->scheduleForDirtyCheck($entity);
2112
            }
2113
        }
2114
        if ($prevManagedCopy !== null) {
2115
            $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, $managedCopy);
2116
        }
2117
        // Mark the managed copy visited as well
2118
        $visited[spl_object_hash($managedCopy)] = $managedCopy;
2119
        $this->cascadeMerge($entity, $managedCopy, $visited);
2120
2121
        return $managedCopy;
2122
    }
2123
2124
    /**
2125
     * Executes a detach operation on the given entity.
2126
     *
2127
     * @param object  $entity
2128
     * @param array   $visited
2129
     * @param boolean $noCascade if true, don't cascade detach operation.
2130
     *
2131
     * @return void
2132
     */
2133
    private function doDetach($entity, array &$visited, $noCascade = false)
2134
    {
2135
        $oid = spl_object_hash($entity);
2136
        if (isset($visited[$oid])) {
2137
            return; // Prevent infinite recursion
2138
        }
2139
        $visited[$oid] = $entity; // mark visited
2140
        switch ($this->getEntityState($entity, self::STATE_DETACHED)) {
2141
            case self::STATE_MANAGED:
2142
                if ($this->isInIdentityMap($entity)) {
2143
                    $this->removeFromIdentityMap($entity);
2144
                }
2145
                unset(
2146
                    $this->entityInsertions[$oid],
2147
                    $this->entityUpdates[$oid],
2148
                    $this->entityDeletions[$oid],
2149
                    $this->entityIdentifiers[$oid],
2150
                    $this->entityStates[$oid],
2151
                    $this->originalEntityData[$oid]
2152
                );
2153
                break;
2154
            case self::STATE_NEW:
2155
            case self::STATE_DETACHED:
2156
                return;
2157
        }
2158
        if (!$noCascade) {
2159
            $this->cascadeDetach($entity, $visited);
2160
        }
2161
    }
2162
2163
}
2164