1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Shared Kernel library. |
5
|
|
|
* |
6
|
|
|
* Copyright (c) 2016-present LIN3S <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace LIN3S\SharedKernel\Event; |
15
|
|
|
|
16
|
|
|
use LIN3S\SharedKernel\Domain\Model\DomainEvent; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @author Beñat Espiña <[email protected]> |
20
|
|
|
*/ |
21
|
|
|
class StoredEvent |
|
|
|
|
22
|
|
|
{ |
23
|
|
|
private $id; |
24
|
|
|
private $type; |
25
|
|
|
private $payload; |
26
|
|
|
private $occurredOn; |
27
|
|
|
private $stream; |
28
|
|
|
|
29
|
|
|
public static function fromDomainEvent(DomainEvent $event, StreamName $stream) : self |
30
|
|
|
{ |
31
|
|
|
$instance = new self(get_class($event), $event->occurredOn(), $stream); |
32
|
|
|
$instance->setPayload($event); |
33
|
|
|
|
34
|
|
|
return $instance; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
private function setPayload(DomainEvent $event) : void |
38
|
|
|
{ |
39
|
|
|
$eventReflection = new \ReflectionClass($event); |
40
|
|
|
foreach ($eventReflection->getProperties() as $property) { |
41
|
|
|
if ('occurredOn' === $property->name) { |
42
|
|
|
continue; |
43
|
|
|
} |
44
|
|
|
$property->setAccessible(true); |
45
|
|
|
// TODO: the following cast is not valid |
46
|
|
|
// what happens when the given property (Value object) |
47
|
|
|
// contains more than one attribute or it has not got implemented |
48
|
|
|
// the __toString() method ?? |
|
|
|
|
49
|
|
|
// Furthermore, in the decodification process we need the class this property |
50
|
|
|
$this->payload[$property->getName()] = (string) $property->getValue($event); |
51
|
|
|
} |
52
|
|
|
$this->payload = json_encode($this->payload); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
private function __construct(string $type, \DateTimeInterface $occurredOn, StreamName $stream) |
56
|
|
|
{ |
57
|
|
|
$this->type = $type; |
58
|
|
|
$this->payload = []; |
59
|
|
|
$this->setOccurredOn($occurredOn); |
60
|
|
|
$this->stream = $stream->name(); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function setOccurredOn(\DateTimeInterface $occurredOn) : void |
64
|
|
|
{ |
65
|
|
|
$occurredOn->setTimezone(new \DateTimeZone('UTC')); |
66
|
|
|
$this->occurredOn = $occurredOn->getTimestamp(); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
public function toArray() : array |
70
|
|
|
{ |
71
|
|
|
return [ |
72
|
|
|
$this->type, |
73
|
|
|
$this->payload, |
74
|
|
|
$this->occurredOn, |
75
|
|
|
$this->stream, |
76
|
|
|
]; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|