Completed
Push — master ( 014532...ba2062 )
by Freek
03:04
created

StoredEvent::scopeWithMetaDataAttributes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
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
use Spatie\SchemalessAttributes\SchemalessAttributes;
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): StoredEvent
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->meta_data = [];
29
        $storedEvent->created_at = now();
30
31
        $storedEvent->save();
32
33
        return $storedEvent;
34
    }
35
36
    public static function getMaxId(): int
37
    {
38
        return DB::table((new static())->getTable())->max('id') ?? 0;
39
    }
40
41
    public function getEventAttribute(): ShouldBeStored
42
    {
43
        return app(EventSerializer::class)->deserialize(
44
           $this->event_class,
45
           $this->getOriginal('event_properties')
46
       );
47
    }
48
49
    public function scopeAfter(Builder $query, int $storedEventId)
50
    {
51
        $query->where('id', '>', $storedEventId);
52
    }
53
54
    public function getMetaDataAttribute(): SchemalessAttributes
55
    {
56
        return SchemalessAttributes::createForModel($this, 'meta_data');
57
    }
58
59
    public function scopeWithMetaDataAttributes(): Builder
60
    {
61
        return SchemalessAttributes::scopeWithSchemalessAttributes('meta_data');
62
    }
63
}
64