Completed
Push — master ( 33591a...530541 )
by Freek
09:49
created

StoredEvent::scopeAfter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
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