1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sebdesign\SM\Traits; |
4
|
|
|
|
5
|
|
|
use SM\Factory\FactoryInterface; |
6
|
|
|
use SM\StateMachine\StateMachine; |
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
8
|
|
|
|
9
|
|
|
trait Statable |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var StateMachine |
13
|
|
|
*/ |
14
|
|
|
protected $stateMachine; |
15
|
|
|
|
16
|
|
|
public function history() |
17
|
|
|
{ |
18
|
|
|
if ($this->isEloquent()) { |
19
|
|
|
return $this->hasMany(self::HISTORY_MODEL_NAME); |
|
|
|
|
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** @var Model $model */ |
23
|
|
|
$model = app(self::HISTORY_MODEL_NAME); |
24
|
|
|
|
25
|
|
|
return $model->where(self::HISTORY_MODEL_FOREIGN_KEY, $this->{self::PRIMARY_KEY}); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function addHistoryLine(array $transitionData) |
29
|
|
|
{ |
30
|
|
|
$transitionData['user_id'] = auth()->id(); |
|
|
|
|
31
|
|
|
|
32
|
|
|
if ($this->isEloquent()) { |
33
|
|
|
$this->save(); |
|
|
|
|
34
|
|
|
|
35
|
|
|
return $this->history()->create($transitionData); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$transitionData[self::HISTORY_MODEL_FOREIGN_KEY] = $this->{self::PRIMARY_KEY}; |
39
|
|
|
/** @var Model $model */ |
40
|
|
|
$model = app(self::HISTORY_MODEL_NAME); |
41
|
|
|
|
42
|
|
|
return $model->create($transitionData); |
|
|
|
|
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function stateIs() |
46
|
|
|
{ |
47
|
|
|
return $this->StateMachine()->getState(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function transition($transition) |
51
|
|
|
{ |
52
|
|
|
return $this->stateMachine()->apply($transition); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function transitionAllowed($transition) |
56
|
|
|
{ |
57
|
|
|
return $this->StateMachine()->can($transition); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @return StateMachine |
62
|
|
|
*/ |
63
|
|
|
public function stateMachine() |
64
|
|
|
{ |
65
|
|
|
if (! $this->stateMachine) { |
66
|
|
|
$this->stateMachine = app(FactoryInterface::class)->get($this, self::SM_CONFIG); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $this->stateMachine; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function isEloquent() |
73
|
|
|
{ |
74
|
|
|
return $this instanceof Model; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
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.