1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\EventProjector; |
4
|
|
|
|
5
|
|
|
use Carbon\Carbon; |
6
|
|
|
use Illuminate\Support\Collection; |
7
|
|
|
use Spatie\EventProjector\Models\StoredEvent; |
8
|
|
|
use Spatie\EventProjector\Models\EloquentStoredEvent; |
9
|
|
|
use Spatie\EventProjector\EventSerializers\EventSerializer; |
10
|
|
|
|
11
|
|
|
class EloquentStoredEventRepository implements StoredEventRepository |
12
|
|
|
{ |
13
|
|
|
public function retrieveAll(string $uuid = null, int $startingFrom = null): Collection |
14
|
|
|
{ |
15
|
|
|
$query = EloquentStoredEvent::query(); |
16
|
|
|
|
17
|
|
|
if ($uuid) { |
|
|
|
|
18
|
|
|
$query->uuid($uuid); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
if ($startingFrom) { |
|
|
|
|
22
|
|
|
$query->startingFrom($startingFrom); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
return $query->get()->map(function (EloquentStoredEvent $storedEvent) { |
26
|
|
|
return $storedEvent->toStoredEvent(); |
27
|
|
|
}); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function persist(ShouldBeStored $event, string $uuid = null): StoredEvent |
31
|
|
|
{ |
32
|
|
|
$eloquentStoredEvent = new EloquentStoredEvent(); |
33
|
|
|
|
34
|
|
|
$eloquentStoredEvent->setRawAttributes([ |
35
|
|
|
'event_properties' => app(EventSerializer::class)->serialize(clone $event), |
36
|
|
|
'aggregate_uuid' => $uuid, |
37
|
|
|
'event_class' => self::getEventClass(get_class($event)), |
38
|
|
|
'meta_data' => json_encode([]), |
39
|
|
|
'created_at' => Carbon::now(), |
40
|
|
|
]); |
41
|
|
|
|
42
|
|
|
$eloquentStoredEvent->save(); |
43
|
|
|
|
44
|
|
|
return $eloquentStoredEvent->toStoredEvent(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function persistMany(array $events, string $uuid = null): Collection |
48
|
|
|
{ |
49
|
|
|
$storedEvents = []; |
50
|
|
|
|
51
|
|
|
foreach ($events as $event) { |
52
|
|
|
$storedEvents[] = self::persist($event, $uuid); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return collect($storedEvents); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function update(StoredEvent $storedEvent): StoredEvent |
59
|
|
|
{ |
60
|
|
|
/** @var EloquentStoredEvent $storedEvent */ |
61
|
|
|
$eloquentStoredEvent = EloquentStoredEvent::find($storedEvent->id); |
62
|
|
|
|
63
|
|
|
$eloquentStoredEvent->update($storedEvent->toArray()); |
64
|
|
|
|
65
|
|
|
return $eloquentStoredEvent->toStoredEvent(); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
View Code Duplication |
private function getEventClass(string $class): string |
|
|
|
|
69
|
|
|
{ |
70
|
|
|
$map = config('event-projector.event_class_map', []); |
71
|
|
|
|
72
|
|
|
if (! empty($map) && in_array($class, $map)) { |
73
|
|
|
return array_search($class, $map, true); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $class; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: