Skip to content

Commit

Permalink
Use jsonSerialize in StateCaster
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrjoniec committed Mar 6, 2024
1 parent 96ff656 commit 1d8de66
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/StateCaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions tests/Dummy/ModelStates/StateB.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,8 @@

class StateB extends ModelState
{
public function jsonSerialize()
{
return ['name' => 'StateB'];
}
}
10 changes: 9 additions & 1 deletion tests/StateCastingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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"}}');
});

0 comments on commit 1d8de66

Please sign in to comment.