|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Domain\Eventing; |
|
4
|
|
|
|
|
5
|
|
|
use Domain\Identity\Identity; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* @author Sebastiaan Hilbers <[email protected]> |
|
9
|
|
|
*/ |
|
10
|
|
|
final class FileEventStore implements EventStore |
|
11
|
|
|
{ |
|
12
|
|
|
private $dataPath; |
|
13
|
|
|
|
|
14
|
|
|
public function __construct($dataPath) |
|
15
|
|
|
{ |
|
16
|
|
|
$this->dataPath = $dataPath; |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Serialize given events and save them do disk. |
|
21
|
|
|
* Actually, each event is a new line inside a single file for each aggregate |
|
22
|
|
|
* |
|
23
|
|
|
* @param \Domain\Eventing\UncommittedEvents $events |
|
24
|
|
|
* @return void |
|
25
|
|
|
*/ |
|
26
|
|
|
public function commit(UncommittedEvents $events) |
|
27
|
|
|
{ |
|
28
|
|
|
$aggregateId = (string) $events[0]->getAggregateIdentity(); |
|
29
|
|
|
$stream = fopen($this->dataPath . '/' . $aggregateId, 'a'); |
|
30
|
|
|
|
|
31
|
|
|
$i = 0; |
|
32
|
|
|
foreach ($events as $event) { |
|
33
|
|
|
$content = ($i > 0) ? PHP_EOL : ''; |
|
34
|
|
|
$content .= serialize($event); |
|
35
|
|
|
fwrite($stream, $content); |
|
36
|
|
|
$i++; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
fclose($stream); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Open the aggregate file and read lines from $min to $max, unserialize and return |
|
44
|
|
|
* immutable event stream as "committed events". |
|
45
|
|
|
* |
|
46
|
|
|
* @param \Domain\Identity\Identity $id |
|
47
|
|
|
* @param integer $offset |
|
48
|
|
|
* @param integer $max |
|
49
|
|
|
* @return \Domain\Eventing\CommittedEvents |
|
50
|
|
|
*/ |
|
51
|
|
|
public function getAggregateHistoryFor(Identity $id, $offset = 0, $max = null) |
|
52
|
|
|
{ |
|
53
|
|
|
$stream = fopen($this->dataPath . '/' . (string) $id, 'r'); |
|
54
|
|
|
|
|
55
|
|
|
$events = []; |
|
56
|
|
|
|
|
57
|
|
|
$i = 0; |
|
58
|
|
|
|
|
59
|
|
|
while (!feof($stream)) { |
|
60
|
|
|
if (!is_null($max) && $i > $max) { |
|
61
|
|
|
break; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
if ($i < $offset) { |
|
65
|
|
|
continue; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
$events[] = unserialize(fgets($stream)); |
|
69
|
|
|
++$i; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
fclose($stream); |
|
73
|
|
|
|
|
74
|
|
|
return new CommittedEvents($id, $events); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|