ldc-boutique-cnc-sable/app/Casts/ShopperServiceCodeCast.php

38 lines
1.2 KiB
PHP
Raw Permalink Normal View History

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