Skip to content

Commit

Permalink
Merge pull request #251 from piotrjoniec/main
Browse files Browse the repository at this point in the history
Implement SerializesCastableAttributes in StateCaster
  • Loading branch information
freekmurze committed Mar 1, 2024
2 parents ed3ef7a + bfc6809 commit d3f7be0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/StateCaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
namespace Spatie\ModelStates;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Contracts\Database\Eloquent\SerializesCastableAttributes;
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;
Expand Down Expand Up @@ -70,6 +71,19 @@ public function set($model, string $key, $value, array $attributes): ?string
return $value::getMorphClass();
}

/**
* @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;
}

private function getStateMapping(): Collection
{
return $this->baseStateClass::getStateMapping();
Expand Down
6 changes: 6 additions & 0 deletions tests/StateCastingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

0 comments on commit d3f7be0

Please sign in to comment.