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

EntityDiff::__invoke()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3.004

Importance

Changes 0
Metric Value
eloc 11
c 0
b 0
f 0
dl 0
loc 18
ccs 12
cts 13
cp 0.9231
rs 9.9
cc 3
nc 1
nop 2
crap 3.004
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