Completed
Push — master ( be9261...7730a8 )
by Freek
01:45
created

StoredEvent::previousInStream()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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