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

HasStates::scopeWhereNotState()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 15
Ratio 100 %

Importance

Changes 0
Metric Value
dl 15
loc 15
rs 9.7666
c 0
b 0
f 0
cc 2
nc 2
nop 3
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
    public function transitionableStates(string $fromClass, string $field): array
161
    {
162
        $stateConfig = self::getStateConfig();
163
164
        $field = $field ?? reset($stateConfig)->field;
165
166
        if (! array_key_exists($field, $stateConfig)) {
167
            throw InvalidConfig::unknownState($field, $this);
168
        }
169
170
        return $stateConfig[$field]->transitionableStates($fromClass);
171
    }
172
173
    /**
174
     * @param string $fromClass
175
     * @param string $toClass
176
     *
177
     * @return \Spatie\ModelStates\Transition|string|null
178
     */
179
    public function resolveTransitionClass(string $fromClass, string $toClass)
180
    {
181
        foreach (static::getStateConfig() as $stateConfig) {
182
            $transitionClass = $stateConfig->resolveTransition($this, $fromClass, $toClass);
183
184
            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...
185
                return $transitionClass;
186
            }
187
        }
188
189
        throw CouldNotPerformTransition::notFound($fromClass, $toClass, $this);
190
    }
191
192
    protected function addState(string $field, string $stateClass): StateConfig
193
    {
194
        $stateConfig = new StateConfig($field, $stateClass);
195
196
        static::$stateFields[$stateConfig->field] = $stateConfig;
197
198
        return $stateConfig;
199
    }
200
201
    /**
202
     * @return \Spatie\ModelStates\StateConfig[]
203
     */
204
    public static function getStateConfig(): array
205
    {
206
        if (static::$stateFields === null) {
207
            static::$stateFields = [];
208
209
            (new static)->registerStates();
210
        }
211
212
        return static::$stateFields ?? [];
213
    }
214
215
    public static function getStates(): Collection
216
    {
217
        return collect(static::getStateConfig())
218
            ->map(function ($state) {
219
                return $state->stateClass::all()->map(function ($stateClass) {
220
                    /** @var \Spatie\ModelStates\State $stateClass */
221
                    return $stateClass::getMorphClass();
222
                });
223
            });
224
    }
225
226
    public static function getStatesFor(string $column): Collection
227
    {
228
        return static::getStates()->get($column, new Collection);
229
    }
230
231
    public static function getDefaultStates(): Collection
232
    {
233
        return collect(static::getStateConfig())
234
            ->map(function ($state) {
235
                return $state->defaultStateClass;
236
            });
237
    }
238
239
    public static function getDefaultStateFor(string $column): string
240
    {
241
        return static::getDefaultStates()->get($column);
242
    }
243
}
244