|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\EventProjector\Models; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Builder; |
|
6
|
|
|
use Illuminate\Support\Facades\DB; |
|
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
8
|
|
|
use Spatie\EventProjector\ShouldBeStored; |
|
9
|
|
|
use Spatie\SchemalessAttributes\SchemalessAttributes; |
|
10
|
|
|
use Spatie\EventProjector\EventSerializers\EventSerializer; |
|
11
|
|
|
|
|
12
|
|
|
class StoredEvent extends Model |
|
13
|
|
|
{ |
|
14
|
|
|
public $guarded = []; |
|
15
|
|
|
|
|
16
|
|
|
public $timestamps = false; |
|
17
|
|
|
|
|
18
|
|
|
public $casts = [ |
|
19
|
|
|
'event_properties' => 'array', |
|
20
|
|
|
'meta_data' => 'array', |
|
21
|
|
|
]; |
|
22
|
|
|
|
|
23
|
|
|
public static function createForEvent(ShouldBeStored $event): self |
|
24
|
|
|
{ |
|
25
|
|
|
$storedEvent = new static(); |
|
26
|
|
|
$storedEvent->event_class = get_class($event); |
|
27
|
|
|
$storedEvent->attributes['event_properties'] = app(EventSerializer::class)->serialize(clone $event); |
|
28
|
|
|
$storedEvent->created_at = now(); |
|
29
|
|
|
$storedEvent->save(); |
|
30
|
|
|
|
|
31
|
|
|
return $storedEvent; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public static function getMaxId(): int |
|
35
|
|
|
{ |
|
36
|
|
|
return DB::table((new static())->getTable())->max('id') ?? 0; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public function getEventAttribute(): ShouldBeStored |
|
40
|
|
|
{ |
|
41
|
|
|
return app(EventSerializer::class)->deserialize( |
|
42
|
|
|
$this->event_class, |
|
43
|
|
|
$this->getOriginal('event_properties') |
|
44
|
|
|
); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function getMetaDataAttribute(): SchemalessAttributes |
|
48
|
|
|
{ |
|
49
|
|
|
return SchemalessAttributes::createForModel($this, 'meta_data'); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public function scopeWithMetaDataAttributes(): Builder |
|
53
|
|
|
{ |
|
54
|
|
|
return SchemalessAttributes::scopeWithSchemalessAttributes('meta_data'); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function scopeAfter(Builder $query, int $storedEventId) |
|
58
|
|
|
{ |
|
59
|
|
|
$query->where('id', '>', $storedEventId); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|