ldc-boutique-cnc-sable/app/Casts/OrderEmployeeCast.php
Jérémy Munsch 3398aacc86
refactor(casts): update exception handling to use fully qualified class names
Refactored exception handling in various cast classes to use fully qualified class names for InvalidArgumentException and UnexpectedValueException.
2026-10-27 09:58:45 +01:00

62 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Casts;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderEmployee;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
/** @implements CastsAttributes<OrderEmployee|null,OrderEmployee|null> */
class OrderEmployeeCast implements CastsAttributes
{
/** @param array<string, mixed> $attributes */
public function get(Model $model, string $key, mixed $value, array $attributes): ?OrderEmployee
{
if (is_null($value)) {
return null;
}
if (! is_string($value)) {
throw new \InvalidArgumentException('The value must be a string.');
}
$data = Arr::wrap(json_decode($value, true));
return new OrderEmployee(
matricule: new Matricule(Arr::string($data, 'matricule')),
firstname: Arr::string($data, 'firstname'),
lastname: Arr::string($data, 'lastname'),
facility: new ShopperEstablishmentCode(Arr::string($data, 'facility')),
site: new ShopperSiteCode(Arr::string($data, 'site')),
service: new ShopperServiceCode(Arr::string($data, 'service')),
);
}
/** @param array<string, mixed> $attributes */
public function set(Model $model, string $key, mixed $value, array $attributes): ?string
{
if ($value === null) {
return null;
}
if (! $value instanceof OrderEmployee) {
throw new \InvalidArgumentException('The given value is not an instance of OrderEmployee.');
}
return json_encode([
'matricule' => $value->matricule->value,
'firstname' => $value->firstname,
'lastname' => $value->lastname,
'facility' => $value->facility->value,
'site' => $value->site->value,
'service' => $value->service->value,
], JSON_THROW_ON_ERROR);
}
}