AssociationCollector::collectToOneAssociation()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 14
rs 10
1
<?php
2
3
namespace Malef\Associate\DoctrineOrm\Collector;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use Malef\Associate\DoctrineOrm\Metadata\AssociationMetadataAdapter;
7
use Malef\Associate\DoctrineOrm\Source\UniqueEntitySet;
8
use Symfony\Component\PropertyAccess\PropertyAccessor;
9
10
class AssociationCollector
11
{
12
    /**
13
     * @var PropertyAccessor
14
     */
15
    protected $propertyAccessor;
16
17
    public function __construct(PropertyAccessor $propertyAccessor)
18
    {
19
        $this->propertyAccessor = $propertyAccessor;
20
    }
21
22
    public function collect(
23
        ArrayCollection $sourceEntities,
24
        AssociationMetadataAdapter $associationMetadataAdapter
25
    ): ArrayCollection {
26
        return $associationMetadataAdapter->isToMany()
27
            ? $this->collectToManyAssociation($sourceEntities, $associationMetadataAdapter)
28
            : $this->collectToOneAssociation($sourceEntities, $associationMetadataAdapter);
29
    }
30
31
    protected function collectToManyAssociation(
32
        ArrayCollection $sourceEntities,
33
        AssociationMetadataAdapter $associationMetadataAdapter
34
    ): ArrayCollection {
35
        $targetEntities = new UniqueEntitySet();
36
37
        foreach ($sourceEntities as $sourceEntity) {
38
            $targetEntities->addMany(
39
                $this->propertyAccessor->getValue($sourceEntity, $associationMetadataAdapter->getName())->getValues()
40
            );
41
        }
42
43
        return $targetEntities->getAll();
44
    }
45
46
    protected function collectToOneAssociation(
47
        ArrayCollection $sourceEntities,
48
        AssociationMetadataAdapter $associationMetadataAdapter
49
    ): ArrayCollection {
50
        $targetEntities = new UniqueEntitySet();
51
52
        foreach ($sourceEntities as $sourceEntity) {
53
            $targetEntity = $this->propertyAccessor->getValue($sourceEntity, $associationMetadataAdapter->getName());
54
            if ($targetEntity) {
55
                $targetEntities->addOne($targetEntity);
56
            }
57
        }
58
59
        return $targetEntities->getAll();
60
    }
61
}
62