Completed
Push — master ( 9e0b65...876221 )
by Freek
08:47 queued 05:37
created

ProjectorStatus::getAllForProjector()   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 1
1
<?php
2
3
namespace Spatie\EventProjector\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Collection;
7
use Spatie\EventProjector\Facades\EventProjectionist;
8
use Spatie\EventProjector\Projectors\Projector;
9
10
class ProjectorStatus extends Model
11
{
12
    public $guarded = [];
13
14
    public static function getForProjector(Projector $projector, StoredEvent $storedEvent = null): self
15
    {
16
        $attributes = ['projector_name' => $projector->getName()];
17
18
        if ($projector->streamBased()) {
19
            $attributes += [
20
                'stream_name' => $storedEvent->stream_name,
21
                'stream_id' => $storedEvent->stream_id,
22
            ];
23
        }
24
25
        return self::firstOrCreate($attributes);
26
    }
27
28
    public static function getAllForProjector(Projector $projector): Collection
29
    {
30
        return static::where('projector_name', $projector->getName())->get();
31
    }
32
33
    public function rememberLastProcessedEvent(StoredEvent $storedEvent): self
34
    {
35
        $this->last_processed_event_id = $storedEvent->id;
36
37
        $attributes = [
38
            'last_processed_event_id' => $storedEvent->id,
39
        ];
40
41
        if ($this->getProjector()->streamBased()) {
42
            $attributes += [
43
                'stream_name' => $storedEvent->stream_name,
44
                'stream_id' => $storedEvent->stream_id,
45
            ];
46
        }
47
48
        $this->update($attributes);
49
50
        return $this;
51
    }
52
53
    public static function hasReceivedAllEvents(Projector $projector): bool
54
    {
55
        $highestEventId = (int) ProjectorStatus::query()
56
            ->where('projector_name', $projector->getName())
57
            ->max('last_processed_event_id') ?? 0;
58
59
        return $highestEventId === StoredEvent::getMaxId();
60
    }
61
62
    public function getProjector(): Projector
63
    {
64
        return EventProjectionist::getProjector($this->projector_name);
65
    }
66
}
67