Completed
Pull Request — master (#32)
by Brent
01:15
created

HasStates::transitionableStates()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Spatie\ModelStates;
4
5
use Illuminate\Support\Collection;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Builder;
8
use Spatie\ModelStates\Exceptions\InvalidConfig;
9
use Spatie\ModelStates\Exceptions\CouldNotPerformTransition;
10
11
/**
12
 * @mixin \Illuminate\Database\Eloquent\Model
13
 */
14
trait HasStates
15
{
16
    /** @var \Spatie\ModelStates\StateConfig[]|null */
17
    protected static $stateFields = null;
18
19
    abstract protected function registerStates(): void;
20
21
    public function __set($name, $value): void
22
    {
23
        if ($value instanceof State) {
24
            $value->setField($name);
25
        }
26
27
        parent::__set($name, $value);
28
    }
29
30
    public static function bootHasStates(): void
31
    {
32
        $serialiseState = function (StateConfig $stateConfig) {
33
            return function (Model $model) use ($stateConfig) {
34
                $value = $model->getAttribute($stateConfig->field);
35
36
                if ($value === null) {
37
                    $value = $stateConfig->defaultStateClass;
38
                }
39
40
                if ($value === null) {
41
                    return;
42
                }
43
44
                $stateClass = $stateConfig->stateClass::resolveStateClass($value);
45
46
                if (! is_subclass_of($stateClass, $stateConfig->stateClass)) {
47
                    throw InvalidConfig::fieldDoesNotExtendState(
48
                        $stateConfig->field,
49
                        $stateConfig->stateClass,
50
                        $stateClass
51
                    );
52
                }
53
54
                $model->setAttribute(
55
                    $stateConfig->field,
56
                    State::resolveStateName($value)
57
                );
58
            };
59
        };
60
61
        $unserialiseState = function (StateConfig $stateConfig) {
62
            return function (Model $model) use ($stateConfig) {
63
                $stateClass = $stateConfig->stateClass::resolveStateClass($model->getAttribute($stateConfig->field));
64
65
                $defaultState = $stateConfig->defaultStateClass
66
                    ? new $stateConfig->defaultStateClass($model)
67
                    : null;
68
69
                /** @var null|\Spatie\ModelStates\State $state */
70
                $state = $defaultState;
71
72
                if(class_exists($stateClass)){
73
                    $state = new $stateClass($model);
74
75
                    $state->setField($stateConfig->field);
76
                }
77
78
                $model->setAttribute(
79
                    $stateConfig->field,
80
                    $state
81
                );
82
            };
83
        };
84
85
        foreach (self::getStateConfig() as $stateConfig) {
86
            static::retrieved($unserialiseState($stateConfig));
87
            static::created($unserialiseState($stateConfig));
88
            static::saved($unserialiseState($stateConfig));
89
90
            static::updating($serialiseState($stateConfig));
91
            static::creating($serialiseState($stateConfig));
92
            static::saving($serialiseState($stateConfig));
93
        }
94
    }
95
96
    public function initializeHasStates(): void
97
    {
98
        foreach (self::getStateConfig() as $stateConfig) {
99
            if (! $stateConfig->defaultStateClass) {
100
                continue;
101
            }
102
103
            $this->{$stateConfig->field} = new $stateConfig->defaultStateClass($this);
104
        }
105
    }
106
107 View Code Duplication
    public function scopeWhereState(Builder $builder, string $field, $states): Builder
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
108
    {
109
        self::getStateConfig();
110
111
        /** @var \Spatie\ModelStates\StateConfig|null $stateConfig */
112
        $stateConfig = self::getStateConfig()[$field] ?? null;
113
114
        if (! $stateConfig) {
115
            throw InvalidConfig::unknownState($field, $this);
116
        }
117
118
        $abstractStateClass = $stateConfig->stateClass;
119
120
        $stateNames = collect((array) $states)->map(function ($state) use ($abstractStateClass) {
121
            return $abstractStateClass::resolveStateName($state);
122
        });
123
124
        return $builder->whereIn($field, $stateNames);
125
    }
126
127 View Code Duplication
    public function scopeWhereNotState(Builder $builder, string $field, $states): Builder
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
128
    {
129
        /** @var \Spatie\ModelStates\StateConfig|null $stateConfig */
130
        $stateConfig = self::getStateConfig()[$field] ?? null;
131
132
        if (! $stateConfig) {
133
            throw InvalidConfig::unknownState($field, $this);
134
        }
135
136
        $stateNames = collect((array) $states)->map(function ($state) use ($stateConfig) {
137
            return $stateConfig->stateClass::resolveStateName($state);
138
        });
139
140
        return $builder->whereNotIn($field, $stateNames);
141
    }
142
143
    /**
144
     * @param \Spatie\ModelStates\State|string $state
145
     * @param string|null $field
146
     */
147
    public function transitionTo($state, string $field = null)
148
    {
149
        $stateConfig = self::getStateConfig();
150
151
        if ($field === null && count($stateConfig) > 1) {
152
            throw CouldNotPerformTransition::couldNotResolveTransitionField($this);
153
        }
154
155
        $field = $field ?? reset($stateConfig)->field;
156
157
        $this->{$field}->transitionTo($state);
158
    }
159
160
    /**
161
     * @param string $fromClass
162
     * @param string $toClass
163
     *
164
     * @return \Spatie\ModelStates\Transition|string|null
165
     */
166
    public function resolveTransitionClass(string $fromClass, string $toClass)
167
    {
168
        foreach (static::getStateConfig() as $stateConfig) {
169
            $transitionClass = $stateConfig->resolveTransition($this, $fromClass, $toClass);
170
171
            if ($transitionClass) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $transitionClass of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
172
                return $transitionClass;
173
            }
174
        }
175
176
        throw CouldNotPerformTransition::notFound($fromClass, $toClass, $this);
177
    }
178
179
    protected function addState(string $field, string $stateClass): StateConfig
180
    {
181
        $stateConfig = new StateConfig($field, $stateClass);
182
183
        static::$stateFields[$stateConfig->field] = $stateConfig;
184
185
        return $stateConfig;
186
    }
187
188
    /**
189
     * @return \Spatie\ModelStates\StateConfig[]
190
     */
191
    public static function getStateConfig(): array
192
    {
193
        if (static::$stateFields === null) {
194
            static::$stateFields = [];
195
196
            (new static)->registerStates();
197
        }
198
199
        return static::$stateFields ?? [];
200
    }
201
202
    public static function getStates(): Collection
203
    {
204
        return collect(static::getStateConfig())
205
            ->map(function ($state) {
206
                return $state->stateClass::all()->map(function ($stateClass) {
207
                    /** @var \Spatie\ModelStates\State $stateClass */
208
                    return $stateClass::getMorphClass();
209
                });
210
            });
211
    }
212
213
    public static function getStatesFor(string $column): Collection
214
    {
215
        return static::getStates()->get($column, new Collection);
216
    }
217
218
    public static function getDefaultStates(): Collection
219
    {
220
        return collect(static::getStateConfig())
221
            ->map(function ($state) {
222
                return $state->defaultStateClass;
223
            });
224
    }
225
226
    public static function getDefaultStateFor(string $column): string
227
    {
228
        return static::getDefaultStates()->get($column);
229
    }
230
}
231