Passed
Push — master ( 7bc9af...373c52 )
by Thorsten
01:56
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\Assert\Assertion;
6
use Daikon\Entity\EntityType\AttributeInterface;
7
use Daikon\Entity\EntityType\EntityTypeInterface;
8
use Daikon\Entity\Exception\UnexpectedType;
9
10
final class EntityDiff
11
{
12 4
    public function __invoke(EntityInterface $left, EntityInterface $right): ValueObjectMap
13
    {
14 4
        $this->assertComparabiliy($left, $right);
15 4
        return ValueObjectMap::forEntity($left, array_reduce(
16 4
            $this->listAtrributeNames($left->getEntityType()),
17 4
            function (array $diff, string $attribute) use ($left, $right): array {
18 4
                if ($this->bothEntitesHaveValueSet($attribute, $left, $right)) {
19 4
                    $diff = $this->addValueIfDifferent($diff, $attribute, $left, $right);
20 1
                } elseif ($left->has($attribute)) {
21 1
                    $diff[$attribute] = $left->get($attribute);
22
                }
23 4
                return $diff;
24 4
            },
25 4
            []
26
        ));
27
    }
28
29 4
    private function assertComparabiliy(EntityInterface $left, EntityInterface $right)
30
    {
31 4
        Assertion::isInstanceOf(
32 4
            $right->getEntityType(),
33 4
            get_class($left->getEntityType()),
34 4
            'Comparing entities of different types is not supported.'
35
        );
36 4
    }
37
38 4
    private function listAtrributeNames(EntityTypeInterface $entityType): array
39
    {
40 4
        return array_keys($entityType->getAttributes()->toArray());
41
    }
42
43 4
    private function bothEntitesHaveValueSet(string $attribute, EntityInterface $left, EntityInterface $right): bool
44
    {
45 4
        return $left->has($attribute) && $right->has($attribute);
46
    }
47
48 4
    private function addValueIfDifferent(array $diff, string $attribute, EntityInterface $left, $right): array
49
    {
50 4
        if (!$left->get($attribute)->equals($right->get($attribute))) {
51 3
            $diff[$attribute] = $left->get($attribute);
52
        }
53 4
        return $diff;
54
    }
55
}
56