Completed
Pull Request — master (#44)
by
unknown
03:19
created

StoredEvent   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 5
dl 0
loc 59
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getMaxId() 0 4 1
A createForEvent() 0 12 1
A getEventAttribute() 0 7 1
A scopeAfter() 0 4 1
A scopeUntil() 0 6 2
A getMetaDataAttribute() 0 4 1
A scopeWithMetaDataAttributes() 0 4 1
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\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): 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 scopeUntil(Builder $query, int $storedEventId = null)
55
    {
56
      if ( $storedEventId !== null ) {
57
        $query->where('id', '>', $storedEventId);
58
      }
59
    }
60
61
    public function getMetaDataAttribute(): SchemalessAttributes
62
    {
63
        return SchemalessAttributes::createForModel($this, 'meta_data');
64
    }
65
66
    public function scopeWithMetaDataAttributes(): Builder
67
    {
68
        return SchemalessAttributes::scopeWithSchemalessAttributes('meta_data');
69
    }
70
}
71