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
|
|
|
|