ldc-boutique-cnc-sable/app/Casts/DiscountValueCast.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

65 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Casts;
use Domain\Enums\DiscountType;
use Domain\Models\ValueObjects\DiscountValue;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Money\Currency;
use Money\Money;
/** @implements CastsAttributes<DiscountValue, DiscountValue> */
class DiscountValueCast implements CastsAttributes
{
/** @param array<string, mixed> $attributes */
public function get(Model $model, string $key, mixed $value, array $attributes): DiscountValue
{
$typeRaw = $attributes['type'] ?? null;
if ($typeRaw === null || (! is_int($typeRaw) && ! is_string($typeRaw))) {
throw new \UnexpectedValueException('The discount type attribute is missing to cast the value.');
}
if ($value === null || (! is_int($value) && ! (is_string($value) && ctype_digit($value)))) {
throw new \UnexpectedValueException('The discount value must be an integer or a numeric string.');
}
$type = DiscountType::tryFrom((int) $typeRaw);
if ($type === null) {
throw new \UnexpectedValueException("Unknown discount type raw value: {$typeRaw}");
}
// Instanciation selon le type
if ($type === DiscountType::PERCENT) {
return DiscountValue::fromPercentage(intval($value));
}
return DiscountValue::fromAmount(
new Money($value, resolve(Currency::class))
);
}
/** @param array<string, mixed> $attributes */
public function set(Model $model, string $key, mixed $value, array $attributes): int
{
if ($value === null) {
throw new \InvalidArgumentException('The value cannot be null.');
}
if (! ($value instanceof DiscountValue)) {
throw new \InvalidArgumentException('The value must be an instance of DiscountValue.');
}
$discountValue = $value->value();
if ($discountValue instanceof Money) {
return (int) $discountValue->getAmount();
}
return $discountValue;
}
}