Skip to content

Commit de46e3e

Browse files
committed
Implement silent handling of same state transitions in StateManager and add corresponding test case
1 parent 7844c20 commit de46e3e

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/StateManager.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,10 @@ public function transition(
4747
$from = $this->getCurrentState($model, $field);
4848
$toValue = $this->extractStateValue($to);
4949

50+
if ($from === $toValue) {
51+
return true;
52+
}
53+
5054
if (! $this->stateMachine->canTransition($from, $toValue)) {
5155
throw new InvalidStateTransitionException($from, $toValue, $field, get_class($model));
5256
}
@@ -78,7 +82,7 @@ public function transition(
7882

7983
return true;
8084
} catch (\Exception $e) {
81-
$model->setAttribute($field, $from);
85+
$model->$field = $from;
8286
$model->save();
8387

8488
throw $e;

tests/Feature/HasStateTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,24 @@ public function it_uses_config_based_model_resolution()
285285
$relatedModel = $states->getRelated();
286286
$this->assertInstanceOf(config('state-history.model'), $relatedModel);
287287
}
288+
289+
#[Test]
290+
public function it_handles_same_state_transitions_silently()
291+
{
292+
$model = new TestModel;
293+
$model->current_state = TestState::Draft->value;
294+
$model->save();
295+
296+
$initialCount = $model->states('state')->count();
297+
298+
$result = $model->transitionTo('state', TestState::Draft);
299+
300+
$this->assertTrue($result);
301+
302+
$this->assertEquals($initialCount, $model->states('state')->count());
303+
304+
$this->assertEquals(TestState::Draft->value, $model->fresh()->current_state);
305+
}
288306
}
289307

290308
enum TestState: string

0 commit comments

Comments
 (0)