Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement SerializesCastableAttributes in StateCaster #251

Merged
merged 2 commits into from
Mar 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});