1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\ModelStates; |
4
|
|
|
|
5
|
|
|
trait HasStates |
6
|
|
|
{ |
7
|
|
|
private array $stateCasts = []; |
|
|
|
|
8
|
|
|
|
9
|
|
|
/** @var \Spatie\ModelStates\StateConfig[] */ |
10
|
|
|
private ?array $stateConfigs = null; |
11
|
|
|
|
12
|
|
|
abstract public function registerStates(): void; |
13
|
|
|
|
14
|
|
|
public static function bootHasStates() |
15
|
|
|
{ |
16
|
|
|
self::creating(function ($model) { |
17
|
|
|
$model->initStateConfigs(); |
18
|
|
|
|
19
|
|
|
/** @var \Spatie\ModelStates\StateConfig $stateConfig */ |
20
|
|
|
foreach ($model->stateConfigs as $stateConfig) { |
21
|
|
|
if ($stateConfig->defaultStateClass === null) { |
22
|
|
|
continue; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
if ($model->{$stateConfig->fieldName} !== null) { |
26
|
|
|
continue; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
$model->{$stateConfig->fieldName} = $stateConfig->defaultStateClass; |
30
|
|
|
} |
31
|
|
|
}); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function getCasts(): array |
35
|
|
|
{ |
36
|
|
|
$this->initStateConfigs(); |
37
|
|
|
|
38
|
|
|
return array_merge( |
39
|
|
|
parent::getCasts(), |
40
|
|
|
$this->stateCasts, |
41
|
|
|
); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
protected function addState(string $fieldName, string $stateClass): StateConfig |
45
|
|
|
{ |
46
|
|
|
$stateConfig = new StateConfig( |
47
|
|
|
static::class, |
48
|
|
|
$fieldName, |
49
|
|
|
$stateClass, |
50
|
|
|
); |
51
|
|
|
|
52
|
|
|
$this->stateCasts[$fieldName] = $stateClass; |
53
|
|
|
|
54
|
|
|
$this->stateConfigs[$fieldName] = $stateConfig; |
55
|
|
|
|
56
|
|
|
return $stateConfig; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function getStateConfig(string $fieldName): StateConfig |
60
|
|
|
{ |
61
|
|
|
return $this->stateConfigs[$fieldName]; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @return \Spatie\ModelStates\StateConfig[] |
66
|
|
|
*/ |
67
|
|
|
public function getStateConfigs(): array |
68
|
|
|
{ |
69
|
|
|
return $this->stateConfigs ?? []; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
private function initStateConfigs(): void |
73
|
|
|
{ |
74
|
|
|
if ($this->stateConfigs === null) { |
75
|
|
|
$this->stateConfigs = []; |
76
|
|
|
$this->registerStates(); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|