Passed
Push — master ( 2bb7f4...7bc9af )
by Thorsten
01:57
created

EntityDiff::addValueIfDifferent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 4
crap 2
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 $left, EntityInterface $right): ValueObjectMap
11
    {
12 4
        $this->assertComparabiliy($left, $right);
13 4
        return ValueObjectMap::forEntity($left, array_reduce(
14 4
            $this->listAtrributeNames($left),
15 4
            function (array $diff, string $attribute) use ($left, $right): array {
16 4
                if ($this->bothEntitesHaveValueSet($attribute, $left, $right)) {
17 4
                    $diff = $this->addValueIfDifferent($diff, $attribute, $left, $right);
18 1
                } elseif ($left->has($attribute)) {
19 1
                    $diff[$attribute] = $left->get($attribute);
20
                }
21 4
                return $diff;
22 4
            },
23 4
            []
24
        ));
25
    }
26
27 4
    private function assertComparabiliy(EntityInterface $left, EntityInterface $right)
28
    {
29 4
        if ($left->getEntityType() !== $right->getEntityType()) {
30
            throw new UnexpectedType('Comparing entities of different types is not supported.');
31
        }
32 4
    }
33
34 4
    private function listAtrributeNames(EntityInterface $entity): array
35
    {
36 4
        return array_keys($entity->getEntityType()->getAttributes()->toArray());
37
    }
38
39 4
    private function bothEntitesHaveValueSet(string $attribute, EntityInterface $left, EntityInterface $right): bool
40
    {
41 4
        return $left->has($attribute) && $right->has($attribute);
42
    }
43
44 4
    private function addValueIfDifferent(array $diff, string $attribute, EntityInterface $left, $right): array
45
    {
46 4
        if (!$left->get($attribute)->equals($right->get($attribute))) {
47 3
            $diff[$attribute] = $left->get($attribute);
48
        }
49 4
        return $diff;
50
    }
51
}
52