1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Kreta package. |
5
|
|
|
* |
6
|
|
|
* (c) Beñat Espiña <[email protected]> |
7
|
|
|
* (c) Gorka Laucirica <[email protected]> |
8
|
|
|
* |
9
|
|
|
* For the full copyright and license information, please view the LICENSE |
10
|
|
|
* file that was distributed with this source code. |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
declare(strict_types=1); |
14
|
|
|
|
15
|
|
|
namespace Kreta\SharedKernel\Infrastructure\Persistence\InMemory\EventStore; |
16
|
|
|
|
17
|
|
|
use Kreta\SharedKernel\Domain\Model\AggregateDoesNotExistException; |
18
|
|
|
use Kreta\SharedKernel\Domain\Model\DomainEventCollection; |
19
|
|
|
use Kreta\SharedKernel\Event\EventStore; |
20
|
|
|
use Kreta\SharedKernel\Event\Stream; |
21
|
|
|
use Kreta\SharedKernel\Event\StreamName; |
22
|
|
|
|
23
|
|
|
class InMemoryEventStore implements EventStore |
24
|
|
|
{ |
25
|
|
|
private $store; |
26
|
|
|
|
27
|
|
|
public function __construct() |
28
|
|
|
{ |
29
|
|
|
$this->store = []; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function appendTo(Stream $stream) : void |
33
|
|
|
{ |
34
|
|
|
foreach ($stream->events() as $event) { |
35
|
|
|
$content = []; |
36
|
|
|
$eventReflection = new \ReflectionClass($event); |
37
|
|
|
foreach ($eventReflection->getProperties() as $property) { |
38
|
|
|
$property->setAccessible(true); |
39
|
|
|
$content[$property->getName()] = $property->getValue($event); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$this->store[] = [ |
43
|
|
|
'stream_name' => $stream->name()->name(), |
44
|
|
|
'type' => get_class($event), |
45
|
|
|
'content' => json_encode($content), |
46
|
|
|
]; |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function streamOfName(StreamName $name) : Stream |
51
|
|
|
{ |
52
|
|
|
$events = new DomainEventCollection(); |
53
|
|
|
foreach ($this->store as $event) { |
54
|
|
|
if ($event['stream_name'] === $name->name()) { |
55
|
|
|
$eventData = json_decode($event['content']); |
56
|
|
|
$eventReflection = new \ReflectionClass($event['type']); |
57
|
|
|
$parameters = $eventReflection->getConstructor()->getParameters(); |
58
|
|
|
$arguments = []; |
59
|
|
|
foreach ($parameters as $parameter) { |
60
|
|
|
foreach ($eventData as $key => $data) { |
61
|
|
|
if ($key === $parameter->getName()) { |
62
|
|
|
$arguments[] = $data; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
$events->add(new $event['type'](...$arguments)); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
if (0 === $events->count()) { |
70
|
|
|
throw new AggregateDoesNotExistException($name->aggregateId()->id()); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return new Stream($name, $events); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|