1 | <?php |
||
13 | |||
14 | private StateConfig $stateConfig; |
||
15 | |||
16 | public static function castUsing() |
||
17 | { |
||
18 | return new StateCaster(static::class); |
||
19 | } |
||
20 | |||
21 | public static function getMorphClass(): string |
||
22 | { |
||
23 | return static::$name ?? static::class; |
||
24 | } |
||
25 | |||
26 | public function __construct(Model $model, StateConfig $stateConfig) |
||
27 | { |
||
28 | $this->model = $model; |
||
29 | $this->stateConfig = $stateConfig; |
||
30 | } |
||
31 | |||
32 | public function transitionTo($newState): Model |
||
33 | { |
||
34 | $newState = $this->resolveState($newState); |
||
35 | |||
36 | $from = static::getMorphClass(); |
||
37 | |||
38 | $to = $newState::getMorphClass(); |
||
39 | |||
40 | if (! $this->stateConfig->isTransitionAllowed($from, $to)) { |
||
41 | throw CouldNotPerformTransition::notFound($from, $to, $this->model); |
||
42 | } |
||
43 | |||
44 | $transition = new DefaultTransition( |
||
45 | $this->model, |
||
46 | $this->stateConfig->fieldName, |
||
47 | $newState |
||
48 | ); |
||
49 | |||
50 | $model = app()->call([$transition, 'handle']); |
||
51 | |||
52 | return $model; |
||
53 | } |
||
54 | |||
55 | public function transitionableStates(): array |
||
56 | { |
||
57 | return $this->stateConfig->transitionableStates(self::getMorphClass()); |
||
58 | } |
||
59 | |||
60 | public function getValue(): string |
||
61 | { |
||
62 | return static::getMorphClass(); |
||
63 | } |
||
64 | |||
65 | public function equals(State ...$otherStates): bool |
||
66 | { |
||
67 | foreach ($otherStates as $otherState) { |
||
68 | if ($this->stateConfig->baseStateClass === $otherState->stateConfig->baseStateClass |
||
69 | && $this->getValue() === $otherState->getValue()) { |
||
70 | return true; |
||
71 | } |
||
72 | } |
||
73 | |||
74 | return false; |
||
75 | } |
||
76 | |||
77 | public function jsonSerialize() |
||
78 | { |
||
79 | return $this->getValue(); |
||
80 | } |
||
81 | |||
82 | public function __toString(): string |
||
83 | { |
||
84 | return $this->getValue(); |
||
85 | } |
||
86 | |||
87 | private function resolveState($state): self |
||
88 | { |
||
89 | if (is_object($state) && is_subclass_of($state, $this->stateConfig->baseStateClass)) { |
||
90 | return $state; |
||
91 | } |
||
92 | |||
93 | if (is_string($state) && is_subclass_of($state, $this->stateConfig->baseStateClass)) { |
||
94 | return new $state($this->model, $this->stateConfig); |
||
95 | } |
||
96 | |||
97 | // TODO: via mapping |
||
98 | } |
||
99 | } |
||
100 |