*/ class DiscountValueCast implements CastsAttributes { /** @param array $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 $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; } }