Passed
Push — master ( a714a7...2bb7f4 )
by Thorsten
02:02
created

EntityDiff::generateDiff()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 13
cts 13
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 11
nc 1
nop 2
crap 5
1
<?php
2
3
namespace Daikon\Entity\Entity;
4
5
use Daikon\Entity\EntityType\AttributeInterface;
6
use Daikon\Entity\Exception\UnexpectedType;
7
8
final class EntityDiff
9
{
10 4
    public function __invoke(EntityInterface $leftEntity, EntityInterface $rightEntity): ValueObjectMap
11
    {
12 4
        $this->assertComparabiliy($leftEntity, $rightEntity);
13 4
        return $this->generateDiff($leftEntity, $rightEntity);
14
    }
15
16 4
    private function assertComparabiliy(EntityInterface $leftEntity, EntityInterface $rightEntity)
17
    {
18 4
        if ($leftEntity->getEntityType() !== $rightEntity->getEntityType()) {
19
            throw new UnexpectedType('Comparing entities of different types is not supported.');
20
        }
21 4
    }
22
23 4
    private function generateDiff(EntityInterface $leftEntity, EntityInterface $rightEntity): ValueObjectMap
24
    {
25 4
        return ValueObjectMap::forEntity($leftEntity, array_reduce(
26 4
            $leftEntity->getEntityType()->getAttributes()->toArray(),
27 4
            function (array $diff, AttributeInterface $attribute) use ($leftEntity, $rightEntity): array {
28 4
                $attrName = $attribute->getName();
29 4
                if ($rightEntity->has($attrName) && $leftEntity->has($attrName)) {
30 4
                    if (!$leftEntity->get($attrName)->equals($rightEntity->get($attrName))) {
31 3
                        $diff[$attrName] = $leftEntity->get($attrName);
32
                    }
33 1
                } elseif ($leftEntity->has($attrName)) {
34 1
                    $diff[$attrName] = $leftEntity->get($attrName);
35
                }
36 4
                return $diff;
37 4
            },
38 4
            []
39
        ));
40
    }
41
}
42