Passed
Push — master ( 7bc9af...373c52 )
by Thorsten
01:56
created

EntityDiff   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 5
dl 0
loc 46
ccs 26
cts 26
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 16 3
A assertComparabiliy() 0 8 1
A listAtrributeNames() 0 4 1
A bothEntitesHaveValueSet() 0 4 2
A addValueIfDifferent() 0 7 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