Passed
Push — master ( dba989...50b90e )
by Mr
06:45
created

EntityDiff   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 86.36%

Importance

Changes 0
Metric Value
wmc 10
eloc 20
dl 0
loc 43
ccs 19
cts 22
cp 0.8636
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 15 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 Daikon\Interop\Assertion;
12
use Daikon\ValueObject\ValueObjectMap;
13
14
final class EntityDiff
15
{
16 1
    public function __invoke(EntityInterface $left, EntityInterface $right): ValueObjectMap
17
    {
18 1
        Assertion::isInstanceOf($right, get_class($left), 'Comparing entities of different types is not supported.');
19
20 1
        return new ValueObjectMap(array_reduce(
21 1
            $left->getAttributeMap()->keys(),
22
            function (array $diff, string $attribute) use ($left, $right): array {
23 1
                if ($this->bothEntitesHaveValueSet($attribute, $left, $right)) {
24 1
                    $diff = $this->addValueIfDifferent($diff, $attribute, $left, $right);
25 1
                } elseif ($left->has($attribute)) {
26
                    $diff[$attribute] = $left->get($attribute);
27
                }
28 1
                return $diff;
29 1
            },
30 1
            []
31
        ));
32
    }
33
34 1
    private function bothEntitesHaveValueSet(string $attribute, EntityInterface $left, EntityInterface $right): bool
35
    {
36 1
        return $left->has($attribute) && $right->has($attribute);
37
    }
38
39 1
    private function addValueIfDifferent(
40
        array $diff,
41
        string $attribute,
42
        EntityInterface $left,
43
        EntityInterface $right
44
    ): array {
45 1
        $left_val = $left->get($attribute, null);
46 1
        $right_val = $right->get($attribute, null);
47 1
        if (is_null($left_val)) {
48
            if (!is_null($right_val)) {
49
                $diff[$attribute] = $left->get($attribute);
50
            }
51
        } else {
52 1
            if (is_null($right_val) || !$left_val->equals($right_val)) {
53 1
                $diff[$attribute] = $left->get($attribute);
54
            }
55
        }
56 1
        return $diff;
57
    }
58
}
59