Completed
Push — master ( 4f3b32...ad97b0 )
by Freek
13:28
created

StoredEvent::scopeWithMetaDataAttributes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
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 Spatie\EventProjector\ShouldBeStored;
8
use Spatie\EventProjector\EventSerializers\EventSerializer;
9
use Spatie\SchemalessAttributes\SchemalessAttributes;
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->created_at = now();
28
        $storedEvent->save();
29
30
        return $storedEvent;
31
    }
32
33
    public static function getMaxId(): int
34
    {
35
        return DB::table((new static())->getTable())->max('id') ?? 0;
36
    }
37
38
    public function getEventAttribute(): ShouldBeStored
39
    {
40
        return app(EventSerializer::class)->deserialize(
41
           $this->event_class,
42
           $this->getOriginal('event_properties')
43
       );
44
    }
45
46
    public function getMetaDataAttribute(): SchemalessAttributes
47
    {
48
        return SchemalessAttributes::createForModel($this, 'extra_attributes');
49
    }
50
51
    public function scopeWithMetaDataAttributes(): Builder
52
    {
53
        return SchemalessAttributes::scopeWithSchemalessAttributes('extra_attributes');
54
    }
55
}
56