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

EntityDiff   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 95.83%

Importance

Changes 0
Metric Value
wmc 10
lcom 0
cbo 5
dl 0
loc 44
ccs 23
cts 24
cp 0.9583
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 16 3
A assertComparabiliy() 0 6 2
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\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