Passed
Push — master ( adc67b...6b2571 )
by Thorsten
05:16 queued 03:10
created

EntityDiff::assertComparibility()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 2
dl 0
loc 8
ccs 6
cts 6
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
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
declare(strict_types=1);
10
11
namespace Daikon\Entity\Entity;
12
13
use Daikon\Entity\Assert\Assertion;
14
15
final class EntityDiff
16
{
17 1
    public function __invoke(EntityInterface $left, EntityInterface $right): ValueObjectMap
18
    {
19 1
        $this->assertComparibility($left, $right);
20 1
        return ValueObjectMap::forEntity($left, array_reduce(
21 1
            $this->listAtrributeNames($left),
22 1
            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 assertComparibility(EntityInterface $left, EntityInterface $right)
35
    {
36 1
        Assertion::isInstanceOf(
37 1
            $right,
38 1
            get_class($left),
39 1
            'Comparing entities of different types is not supported.'
40
        );
41 1
    }
42
43 1
    private function listAtrributeNames(EntityInterface $entity): array
44
    {
45 1
        return array_keys($entity->getAttributeMap()->toArray());
46
    }
47
48 1
    private function bothEntitesHaveValueSet(string $attribute, EntityInterface $left, EntityInterface $right): bool
49
    {
50 1
        return $left->has($attribute) && $right->has($attribute);
51
    }
52
53 1
    private function addValueIfDifferent(
54
        array $diff,
55
        string $attribute,
56
        EntityInterface $left,
57
        EntityInterface $right
58
    ): array {
59 1
        if (!$left->get($attribute)->equals($right->get($attribute))) {
60 1
            $diff[$attribute] = $left->get($attribute);
61
        }
62 1
        return $diff;
63
    }
64
}
65