From 6cf26be49d694a2dc8148c5da56a97a566501438 Mon Sep 17 00:00:00 2001 From: Piotr Joniec Date: Wed, 28 Feb 2024 22:37:37 +0100 Subject: [PATCH 1/2] Implement SerializesCastableAttributes in StateCaster --- src/StateCaster.php | 9 ++++++++- tests/StateCastingTest.php | 6 ++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/StateCaster.php b/src/StateCaster.php index ab2899a..d3530da 100644 --- a/src/StateCaster.php +++ b/src/StateCaster.php @@ -3,10 +3,12 @@ namespace Spatie\ModelStates; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; +use Illuminate\Contracts\Database\Eloquent\SerializesCastableAttributes; +use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; use Spatie\ModelStates\Exceptions\UnknownState; -class StateCaster implements CastsAttributes +class StateCaster implements CastsAttributes, SerializesCastableAttributes { /** @var string|\Spatie\ModelStates\State */ private string $baseStateClass; @@ -70,6 +72,11 @@ public function set($model, string $key, $value, array $attributes): ?string return $value::getMorphClass(); } + public function serialize(Model $model, string $key, mixed $value, array $attributes) + { + return $value instanceof State ? $value->getValue() : $value; + } + private function getStateMapping(): Collection { return $this->baseStateClass::getStateMapping(); diff --git a/tests/StateCastingTest.php b/tests/StateCastingTest.php index 4437bff..bdf006f 100644 --- a/tests/StateCastingTest.php +++ b/tests/StateCastingTest.php @@ -136,3 +136,9 @@ public function registerStates(): void expect($model->state->getField())->toEqual('state'); }); + +it('serializes to a value', function() { + $model = new TestModel(); + + expect($model->toArray()['state'])->toBe(StateA::class); +}); From bfc68094ab3d32a873fa89b2093cccca1400e2ec Mon Sep 17 00:00:00 2001 From: Piotr Joniec Date: Thu, 29 Feb 2024 14:31:29 +0100 Subject: [PATCH 2/2] Fix declaration for backward compatibility --- src/StateCaster.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/StateCaster.php b/src/StateCaster.php index d3530da..0eafbc0 100644 --- a/src/StateCaster.php +++ b/src/StateCaster.php @@ -4,7 +4,6 @@ use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Contracts\Database\Eloquent\SerializesCastableAttributes; -use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; use Spatie\ModelStates\Exceptions\UnknownState; @@ -72,7 +71,15 @@ public function set($model, string $key, $value, array $attributes): ?string return $value::getMorphClass(); } - public function serialize(Model $model, string $key, mixed $value, array $attributes) + /** + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param mixed $value + * @param array $attributes + * + * @return mixed + */ + public function serialize($model, string $key, $value, array $attributes) { return $value instanceof State ? $value->getValue() : $value; }