Completed
Pull Request — master (#108)
by Brent
14:43
created

HasStates::canTransitionTo()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.2408
c 0
b 0
f 0
cc 5
nc 3
nop 2
1
<?php
2
3
namespace Spatie\ModelStates;
4
5
trait HasStates
6
{
7
    private array $stateCasts = [];
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_ARRAY, expecting T_FUNCTION or T_CONST
Loading history...
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