1
|
|
|
<?php namespace C4tech\RayEmitter\Domain; |
2
|
|
|
|
3
|
|
|
use C4tech\RayEmitter\Contracts\Domain\Aggregate as AggregateInterface; |
4
|
|
|
use C4tech\RayEmitter\Contracts\Domain\Command as CommandInterface; |
5
|
|
|
use C4tech\RayEmitter\Contracts\Domain\Repository as RepositoryInterface; |
6
|
|
|
use C4tech\RayEmitter\Facades\EventStore; |
7
|
|
|
use C4tech\RayEmitter\Exceptions\OutdatedSequence; |
8
|
|
|
use C4tech\RayEmitter\Exceptions\SequenceMismatch; |
9
|
|
|
|
10
|
|
|
abstract class Repository implements RepositoryInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @inheritDoc |
14
|
|
|
*/ |
15
|
2 |
|
public static function find($identifier) |
16
|
|
|
{ |
17
|
2 |
|
$aggregate = static::create(); |
18
|
2 |
|
static::restore($identifier, $aggregate); |
19
|
|
|
|
20
|
2 |
|
return $aggregate; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @inheritDoc |
25
|
|
|
*/ |
26
|
1 |
|
public static function getEntity($identifier) |
27
|
|
|
{ |
28
|
1 |
|
$aggregate = static::find($identifier); |
29
|
|
|
|
30
|
1 |
|
return $aggregate->getEntity(); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @inheritDoc |
35
|
|
|
*/ |
36
|
3 |
|
public static function handle(CommandInterface $command) |
37
|
|
|
{ |
38
|
3 |
|
$aggregate = static::create(); |
39
|
3 |
|
if ($aggregate_id = $command->getAggregateId()) { |
40
|
2 |
|
static::restore($aggregate_id, $aggregate); |
41
|
2 |
|
} |
42
|
|
|
|
43
|
|
|
// Optimistic concurrency handling |
44
|
3 |
|
$expected = $command->getExpectedSequence(); |
45
|
3 |
|
$current = $aggregate->getSequence(); |
46
|
3 |
|
if ($expected < $current) { |
47
|
1 |
|
throw new OutdatedSequence( |
48
|
1 |
|
sprintf( |
49
|
1 |
|
'The Aggregate %s has newer data than expected.', |
50
|
1 |
|
get_class($aggregate) |
51
|
1 |
|
), |
52
|
|
|
409 |
53
|
1 |
|
); |
54
|
2 |
|
} elseif ($expected > $current) { |
55
|
1 |
|
throw new SequenceMismatch( |
56
|
1 |
|
sprintf( |
57
|
1 |
|
'The Aggregate %s is expected to have more data than it does', |
58
|
1 |
|
get_class($aggregate) |
59
|
1 |
|
), |
60
|
|
|
422 |
61
|
1 |
|
); |
62
|
|
|
} |
63
|
|
|
|
64
|
1 |
|
$aggregate->handle($command); |
65
|
1 |
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Restore |
69
|
|
|
* |
70
|
|
|
* Hydrate an aggregate with its recorded events. |
71
|
|
|
* @param string $identifier Aggregate root entity identifier. |
72
|
|
|
* @param AggregateInterface &$aggregate (Fresh) Aggregate to hydrate. |
73
|
|
|
* @return void |
74
|
|
|
*/ |
75
|
4 |
|
protected static function restore($identifier, AggregateInterface &$aggregate) |
76
|
|
|
{ |
77
|
4 |
|
$events = EventStore::getFor($identifier); |
78
|
4 |
|
$aggregate->hydrate($events); |
79
|
4 |
|
} |
80
|
|
|
} |
81
|
|
|
|