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

HasStates::__set()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Spatie\ModelStates;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Support\Collection;
8
use Spatie\ModelStates\Exceptions\CouldNotPerformTransition;
9
use Spatie\ModelStates\Exceptions\InvalidConfig;
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
        $serializeState = 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
        $unserializeState = 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($unserializeState($stateConfig));
87
            static::created($unserializeState($stateConfig));
88
            static::saved($unserializeState($stateConfig));
89
90
            static::updating($serializeState($stateConfig));
91
            static::creating($serializeState($stateConfig));
92
            static::saving($serializeState($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
     * @return \Illuminate\Database\Eloquent\Model
148
     */
149
    public function transitionTo($state, string $field = null)
150
    {
151
        $stateConfig = self::getStateConfig();
152
153
        if ($field === null && count($stateConfig) > 1) {
154
            throw CouldNotPerformTransition::couldNotResolveTransitionField($this);
155
        }
156
157
        $field = $field ?? reset($stateConfig)->field;
158
159
        return $this->{$field}->transitionTo($state);
160
    }
161
162
    /**
163
     * @param string $fromClass
164
     * @param string $toClass
165
     *
166
     * @return \Spatie\ModelStates\Transition|string|null
167
     */
168
    public function resolveTransitionClass(string $fromClass, string $toClass)
169
    {
170
        foreach (static::getStateConfig() as $stateConfig) {
171
            $transitionClass = $stateConfig->resolveTransition($this, $fromClass, $toClass);
172
173
            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...
174
                return $transitionClass;
175
            }
176
        }
177
178
        throw CouldNotPerformTransition::notFound($fromClass, $toClass, $this);
179
    }
180
181
    protected function addState(string $field, string $stateClass): StateConfig
182
    {
183
        $stateConfig = new StateConfig($field, $stateClass);
184
185
        static::$stateFields[$stateConfig->field] = $stateConfig;
186
187
        return $stateConfig;
188
    }
189
190
    /**
191
     * @return \Spatie\ModelStates\StateConfig[]
192
     */
193
    public static function getStateConfig(): array
194
    {
195
        if (static::$stateFields === null) {
196
            static::$stateFields = [];
197
198
            (new static)->registerStates();
199
        }
200
201
        return static::$stateFields ?? [];
202
    }
203
204
    public static function getStates(): Collection
205
    {
206
        return collect(static::getStateConfig())
207
            ->map(function ($state) {
208
                return $state->stateClass::all()->map(function ($stateClass) {
209
                    /** @var \Spatie\ModelStates\State $stateClass */
210
                    return $stateClass::getMorphClass();
211
                });
212
            });
213
    }
214
215
    public static function getStatesFor(string $column): Collection
216
    {
217
        return static::getStates()->get($column, new Collection);
218
    }
219
220
    public static function getDefaultStates(): Collection
221
    {
222
        return collect(static::getStateConfig())
223
            ->map(function ($state) {
224
                return $state->defaultStateClass;
225
            });
226
    }
227
228
    public static function getDefaultStateFor(string $column): string
229
    {
230
        return static::getDefaultStates()->get($column);
231
    }
232
}
233