34 lines
949 B
PHP
34 lines
949 B
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Casts;
|
|
|
|
use Domain\Models\ValueObjects\Code;
|
|
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
/** @implements CastsAttributes<Code,Code> */
|
|
class CodeCast implements CastsAttributes
|
|
{
|
|
/** @param array<string, mixed> $attributes */
|
|
public function get(Model $model, string $key, mixed $value, array $attributes): Code
|
|
{
|
|
if ($value === null || ! is_string($value)) {
|
|
throw new \UnexpectedValueException('Code must be a string.');
|
|
}
|
|
|
|
return new Code($value);
|
|
}
|
|
|
|
/** @param array<string, mixed> $attributes */
|
|
public function set(Model $model, string $key, mixed $value, array $attributes): string
|
|
{
|
|
|
|
if (! $value instanceof Code) {
|
|
throw new \UnexpectedValueException('The given value is not an instance of Code.');
|
|
}
|
|
|
|
return $value->value;
|
|
}
|
|
}
|