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

44 lines
1.3 KiB
PHP

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