Completed
Pull Request — master (#21)
by
unknown
01:15
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 Spatie\ModelStates\State;
6
use Illuminate\Support\Collection;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Database\Eloquent\Builder;
9
use Spatie\ModelStates\Exceptions\InvalidConfig;
10
use Spatie\ModelStates\Exceptions\CouldNotPerformTransition;
11
12
/**
13
 * @mixin \Illuminate\Database\Eloquent\Model
14
 */
15
trait HasStates
16
{
17
    /** @var \Spatie\ModelStates\StateConfig[]|null */
18
    protected static $stateFields = null;
19
20
    abstract protected function registerStates(): void;
21
22
    public static function bootHasStates(): void
23
    {
24
        $serialiseState = function (StateConfig $stateConfig) {
25
            return function (Model $model) use ($stateConfig) {
26
                $value = $model->getAttribute($stateConfig->field);
27
28
                if ($value === null) {
29
                    $value = $stateConfig->defaultStateClass;
30
                }
31
32
                if ($value === null) {
33
                    return;
34
                }
35
36
                $stateClass = $stateConfig->stateClass::resolveStateClass($value);
37
38
                if (! is_subclass_of($stateClass, $stateConfig->stateClass)) {
39
                    throw InvalidConfig::fieldDoesNotExtendState(
40
                        $stateConfig->field,
41
                        $stateConfig->stateClass,
42
                        $stateClass
43
                    );
44
                }
45
46
                $model->setAttribute(
47
                    $stateConfig->field,
48
                    State::resolveStateName($value)
49
                );
50
            };
51
        };
52
53
        $unserialiseState = function (StateConfig $stateConfig) {
54
            return function (Model $model) use ($stateConfig) {
55
                $stateClass = $stateConfig->stateClass::resolveStateClass($model->getAttribute($stateConfig->field));
56
57
                $defaultState = $stateConfig->defaultStateClass
58
                    ? new $stateConfig->defaultStateClass($model)
59
                    : null;
60
61
                $model->setAttribute(
62
                    $stateConfig->field,
63
                    class_exists($stateClass)
64
                        ? new $stateClass($model)
65
                        : $defaultState
66
                );
67
            };
68
        };
69
70
        foreach (self::getStateConfig() as $stateConfig) {
71
            static::retrieved($unserialiseState($stateConfig));
72
            static::created($unserialiseState($stateConfig));
73
            static::saved($unserialiseState($stateConfig));
74
75
            static::updating($serialiseState($stateConfig));
76
            static::creating($serialiseState($stateConfig));
77
            static::saving($serialiseState($stateConfig));
78
        }
79
    }
80
81
    public function initializeHasStates(): void
82
    {
83
        foreach (self::getStateConfig() as $stateConfig) {
84
            if (! $stateConfig->defaultStateClass) {
85
                continue;
86
            }
87
88
            $this->{$stateConfig->field} = new $stateConfig->defaultStateClass($this);
89
        }
90
    }
91
92 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...
93
    {
94
        self::getStateConfig();
95
96
        /** @var \Spatie\ModelStates\StateConfig|null $stateConfig */
97
        $stateConfig = self::getStateConfig()[$field] ?? null;
98
99
        if (! $stateConfig) {
100
            throw InvalidConfig::unknownState($field, $this);
101
        }
102
103
        $abstractStateClass = $stateConfig->stateClass;
104
105
        $stateNames = collect((array) $states)->map(function ($state) use ($abstractStateClass) {
106
            return $abstractStateClass::resolveStateName($state);
107
        });
108
109
        return $builder->whereIn($field, $stateNames);
110
    }
111
112 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...
113
    {
114
        /** @var \Spatie\ModelStates\StateConfig|null $stateConfig */
115
        $stateConfig = self::getStateConfig()[$field] ?? null;
116
117
        if (! $stateConfig) {
118
            throw InvalidConfig::unknownState($field, $this);
119
        }
120
121
        $stateNames = collect((array) $states)->map(function ($state) use ($stateConfig) {
122
            return $stateConfig->stateClass::resolveStateName($state);
123
        });
124
125
        return $builder->whereNotIn($field, $stateNames);
126
    }
127
128
    /**
129
     * @param \Spatie\ModelStates\State|string $state
130
     * @param string|null $field
131
     */
132
    public function transitionTo($state, string $field = null)
133
    {
134
        $stateConfig = self::getStateConfig();
135
136
        if ($field === null && count($stateConfig) > 1) {
137
            throw CouldNotPerformTransition::couldNotResolveTransitionField($this);
138
        }
139
140
        $field = $field ?? reset($stateConfig)->field;
141
142
        $this->{$field}->transitionTo($state);
143
    }
144
145
    /**
146
     * @param string $fromClass
147
     * @param string $toClass
148
     *
149
     * @return \Spatie\ModelStates\Transition|string|null
150
     */
151
    public function resolveTransitionClass(string $fromClass, string $toClass)
152
    {
153
        foreach (static::getStateConfig() as $stateConfig) {
154
            $transitionClass = $stateConfig->resolveTransition($this, $fromClass, $toClass);
155
156
            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...
157
                return $transitionClass;
158
            }
159
        }
160
161
        throw CouldNotPerformTransition::notFound($fromClass, $toClass, $this);
162
    }
163
164
    protected function addState(string $field, string $stateClass): StateConfig
165
    {
166
        $stateConfig = new StateConfig($field, $stateClass);
167
168
        static::$stateFields[$stateConfig->field] = $stateConfig;
169
170
        return $stateConfig;
171
    }
172
173
    /**
174
     * @return \Spatie\ModelStates\StateConfig[]
175
     */
176
    private static function getStateConfig(): array
177
    {
178
        if (static::$stateFields === null) {
179
            static::$stateFields = [];
180
181
            (new static)->registerStates();
182
        }
183
184
        return static::$stateFields ?? [];
185
    }
186
187
    public static function getStates(): Collection
188
    {
189
        return collect(static::getStateConfig())
190
            ->map(function ($state) {
191
                return $state->stateClass::all();
192
            });
193
    }
194
195
196
    public static function getStatesFor(string $column): Collection
197
    {
198
        return static::getStates()->get($column, new Collection);
199
    }
200
201
    public static function getDefaultStates(): Collection
202
    {
203
        return collect(static::getStateConfig())
204
            ->map(function ($state) {
205
                return $state->defaultStateClass;
206
            });
207
    }
208
209
    public static function getDefaultStateFor(string $column): string
210
    {
211
        return static::getDefaultStates()->get($column);
212
    }
213
}
214