42 lines
1.1 KiB
PHP
42 lines
1.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Domain\Shared\Casts;
|
|
|
|
use App\Domain\Shared\ValueObjects\Uuid;
|
|
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Ramsey\Uuid\UuidInterface;
|
|
use Spatie\LaravelData\Casts\Cast;
|
|
use Spatie\LaravelData\Support\Creation\CreationContext;
|
|
use Spatie\LaravelData\Support\DataProperty;
|
|
|
|
class UuidCast implements CastsAttributes, Cast
|
|
{
|
|
public function get(Model $model, string $key, mixed $value, array $attributes): ?Uuid
|
|
{
|
|
if (is_null($value)) {
|
|
return null;
|
|
}
|
|
return Uuid::fromString($value);
|
|
}
|
|
|
|
public function set(Model $model, string $key, mixed $value, array $attributes)
|
|
{
|
|
if (is_null($value)) {
|
|
return [$key => null];
|
|
}
|
|
|
|
if ($value instanceof UuidInterface) {
|
|
return [$key => $value->toString()];
|
|
}
|
|
|
|
return [$key => Uuid::fromString((string) $value)->toString()];
|
|
}
|
|
|
|
public function cast(DataProperty $property, mixed $value, array $properties, CreationContext $context): mixed
|
|
{
|
|
return Uuid::fromString((string) $value);
|
|
}
|
|
} |