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

66 lines
2.1 KiB
PHP
Raw Permalink Normal View History

2026-06-14 21:32:07 +02:00
<?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.');
2026-06-14 21:32:07 +02:00
}
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.');
2026-06-14 21:32:07 +02:00
}
$type = DiscountType::tryFrom((int) $typeRaw);
if ($type === null) {
throw new \UnexpectedValueException("Unknown discount type raw value: {$typeRaw}");
2026-06-14 21:32:07 +02:00
}
// 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.');
2026-06-14 21:32:07 +02:00
}
if (! ($value instanceof DiscountValue)) {
throw new \InvalidArgumentException('The value must be an instance of DiscountValue.');
2026-06-14 21:32:07 +02:00
}
$discountValue = $value->value();
if ($discountValue instanceof Money) {
return (int) $discountValue->getAmount();
}
return $discountValue;
}
}