1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sebdesign\SM\Traits; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use SM\Factory\FactoryInterface; |
7
|
|
|
use SM\StateMachine\StateMachine; |
8
|
|
|
|
9
|
|
|
trait Statable |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var StateMachine $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
|
|
|
return $this->history()->create($transitionData); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$transitionData[self::HISTORY_MODEL['foreign_key']] = $this->{self::PRIMARY_KEY}; |
38
|
|
|
/** @var Model $model */ |
39
|
|
|
$model = app(self::HISTORY_MODEL['name']); |
40
|
|
|
|
41
|
|
|
return $model->create($transitionData); |
|
|
|
|
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function stateIs() |
45
|
|
|
{ |
46
|
|
|
return $this->StateMachine()->getState(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function transition($transition) |
50
|
|
|
{ |
51
|
|
|
return $this->stateMachine()->apply($transition); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function transitionAllowed($transition) |
55
|
|
|
{ |
56
|
|
|
return $this->StateMachine()->can($transition); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @return StateMachine |
61
|
|
|
*/ |
62
|
|
|
public function stateMachine() |
63
|
|
|
{ |
64
|
|
|
if (!$this->stateMachine) { |
65
|
|
|
$this->stateMachine = app(FactoryInterface::class)->get($this, self::SM_CONFIG); |
66
|
|
|
} |
67
|
|
|
return $this->stateMachine; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function isEloquent() |
71
|
|
|
{ |
72
|
|
|
return $this instanceof Model; |
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.