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

EntityDiff::__invoke()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3.0067

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 15
ccs 10
cts 11
cp 0.9091
rs 9.9666
c 0
b 0
f 0
cc 3
nc 1
nop 2
crap 3.0067
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