Passed
Push — master ( d25e4d...dba989 )
by Mr
06:54
created

EntityDiff   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 87.5%

Importance

Changes 0
Metric Value
wmc 10
eloc 22
c 0
b 0
f 0
dl 0
loc 46
ccs 21
cts 24
cp 0.875
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 18 3
A bothEntitesHaveValueSet() 0 3 2
A addValueIfDifferent() 0 18 5
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of the daikon-cqrs/entity project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Daikon\Entity;
10
11
use Assert\Assert;
12
use Daikon\ValueObject\ValueObjectMap;
13
14
final class EntityDiff
15
{
16 1
    public function __invoke(EntityInterface $left, EntityInterface $right): ValueObjectMap
17
    {
18 1
        Assert::that($right)->isInstanceOf(
19 1
            get_class($left),
20 1
            'Comparing entities of different types is not supported.'
21
        );
22
23 1
        return new ValueObjectMap(array_reduce(
24 1
            $left->getAttributeMap()->keys(),
25
            function (array $diff, string $attribute) use ($left, $right): array {
26 1
                if ($this->bothEntitesHaveValueSet($attribute, $left, $right)) {
27 1
                    $diff = $this->addValueIfDifferent($diff, $attribute, $left, $right);
28 1
                } elseif ($left->has($attribute)) {
29
                    $diff[$attribute] = $left->get($attribute);
30
                }
31 1
                return $diff;
32 1
            },
33 1
            []
34
        ));
35
    }
36
37 1
    private function bothEntitesHaveValueSet(string $attribute, EntityInterface $left, EntityInterface $right): bool
38
    {
39 1
        return $left->has($attribute) && $right->has($attribute);
40
    }
41
42 1
    private function addValueIfDifferent(
43
        array $diff,
44
        string $attribute,
45
        EntityInterface $left,
46
        EntityInterface $right
47
    ): array {
48 1
        $left_val = $left->get($attribute, null);
49 1
        $right_val = $right->get($attribute, null);
50 1
        if (is_null($left_val)) {
51
            if (!is_null($right_val)) {
52
                $diff[$attribute] = $left->get($attribute);
53
            }
54
        } else {
55 1
            if (is_null($right_val) || !$left_val->equals($right_val)) {
56 1
                $diff[$attribute] = $left->get($attribute);
57
            }
58
        }
59 1
        return $diff;
60
    }
61
}
62