diff --git a/src/StateCaster.php b/src/StateCaster.php index 0eafbc0..b417293 100644 --- a/src/StateCaster.php +++ b/src/StateCaster.php @@ -81,7 +81,7 @@ public function set($model, string $key, $value, array $attributes): ?string */ public function serialize($model, string $key, $value, array $attributes) { - return $value instanceof State ? $value->getValue() : $value; + return $value instanceof State ? $value->jsonSerialize() : $value; } private function getStateMapping(): Collection diff --git a/tests/Dummy/ModelStates/StateB.php b/tests/Dummy/ModelStates/StateB.php index ba5925d..5b87b58 100644 --- a/tests/Dummy/ModelStates/StateB.php +++ b/tests/Dummy/ModelStates/StateB.php @@ -4,4 +4,8 @@ class StateB extends ModelState { + public function jsonSerialize() + { + return ['name' => 'StateB']; + } } diff --git a/tests/StateCastingTest.php b/tests/StateCastingTest.php index bdf006f..476cc94 100644 --- a/tests/StateCastingTest.php +++ b/tests/StateCastingTest.php @@ -137,8 +137,16 @@ public function registerStates(): void expect($model->state->getField())->toEqual('state'); }); -it('serializes to a value', function() { +it('serializes to a value when calling toArray', function() { $model = new TestModel(); expect($model->toArray()['state'])->toBe(StateA::class); }); + +it('respects jsonSerialize in state classes', function() { + $model = new TestModel([ + 'state' => StateB::class, + ]); + + expect($model->toJson())->toBe('{"state":{"name":"StateB"}}'); +});