1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\ModelStatus; |
4
|
|
|
|
5
|
|
|
use DB; |
6
|
|
|
use Illuminate\Database\Eloquent\Builder; |
7
|
|
|
use Spatie\ModelStatus\Exceptions\InvalidStatus; |
8
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany; |
9
|
|
|
|
10
|
|
|
trait HasStatuses |
11
|
|
|
{ |
12
|
|
|
public function statuses(): MorphMany |
13
|
|
|
{ |
14
|
|
|
return $this->morphMany(ModelStatusServiceProvider::getStatusModel(), 'model')->latest(); |
|
|
|
|
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public function status(): ?Status |
18
|
|
|
{ |
19
|
|
|
return $this->latestStatus(); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function setStatus(string $name, string $reason = ''): self |
23
|
|
|
{ |
24
|
|
|
if (! $this->isValidStatus($name, $reason)) { |
25
|
|
|
throw InvalidStatus::create($name, $reason); |
|
|
|
|
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
$attributes = compact('name', 'reason'); |
29
|
|
|
|
30
|
|
|
$this->statuses()->create($attributes); |
31
|
|
|
|
32
|
|
|
return $this; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function isValidStatus(string $name, string $reason = ''): bool |
|
|
|
|
36
|
|
|
{ |
37
|
|
|
return true; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param string|array $names |
42
|
|
|
* @return null|Status |
43
|
|
|
*/ |
44
|
|
|
public function latestStatus(...$names): ?Status |
45
|
|
|
{ |
46
|
|
|
$names = is_array($names) ? array_flatten($names) : func_get_args(); |
47
|
|
|
|
48
|
|
|
if (count($names) < 1) { |
49
|
|
|
return $this->statuses()->orderByDesc('id')->first(); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $this->statuses()->whereIn('name', $names)->orderByDesc('id')->first(); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function scopeHasStatus(Builder $builder, string $name) |
56
|
|
|
{ |
57
|
|
|
return $builder |
58
|
|
|
->whereHas('statuses', function (Builder $query) use ($name) { |
59
|
|
|
$query |
60
|
|
|
->where('name', $name) |
61
|
|
|
->whereIn('id', function ($query) use ($name) { |
62
|
|
|
$query |
63
|
|
|
->select(DB::raw('max(id)')) |
64
|
|
|
->from('statuses') |
65
|
|
|
->groupBy('model_id'); |
66
|
|
|
}); |
67
|
|
|
}); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function getStatusAttribute(): string |
71
|
|
|
{ |
72
|
|
|
return $this->latestStatus(); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.