|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace StdOut\SimpleDataObjects\Casts; |
| 6 | + |
| 7 | +use InvalidArgumentException; |
| 8 | +use StdOut\SimpleDataObjects\Contracts\CastsValue; |
| 9 | +use StdOut\SimpleDataObjects\ValueObjects\Money; |
| 10 | + |
| 11 | +/** |
| 12 | + * Casts to/from `Money`, storing the amount in minor units (integer cents) |
| 13 | + * to avoid float rounding error. Accepts int minor units, a numeric decimal |
| 14 | + * string, or an `['amount' => ..., 'currency' => ...]` array on hydration; |
| 15 | + * serializes back to int minor units — the currency is fixed per field via |
| 16 | + * the constructor, so it isn't repeated in the serialized payload. |
| 17 | + */ |
| 18 | +final class MoneyCast implements CastsValue |
| 19 | +{ |
| 20 | + public function __construct( |
| 21 | + private readonly string $currency, |
| 22 | + private readonly int $decimals = 2, |
| 23 | + ) {} |
| 24 | + |
| 25 | + public static function __set_state(array $state): self |
| 26 | + { |
| 27 | + return new self($state['currency'], $state['decimals']); |
| 28 | + } |
| 29 | + |
| 30 | + public function get(mixed $value): ?Money |
| 31 | + { |
| 32 | + if ($value === null) { |
| 33 | + return null; |
| 34 | + } |
| 35 | + |
| 36 | + if ($value instanceof Money) { |
| 37 | + $this->assertCurrency($value->currency); |
| 38 | + |
| 39 | + return $value; |
| 40 | + } |
| 41 | + |
| 42 | + if (is_array($value)) { |
| 43 | + $currency = $value['currency'] ?? $this->currency; |
| 44 | + $this->assertCurrency($currency); |
| 45 | + |
| 46 | + return new Money($this->resolveAmount($value['amount']), $currency); |
| 47 | + } |
| 48 | + |
| 49 | + return new Money($this->resolveAmount($value), $this->currency); |
| 50 | + } |
| 51 | + |
| 52 | + public function set(mixed $value): ?int |
| 53 | + { |
| 54 | + if ($value === null) { |
| 55 | + return null; |
| 56 | + } |
| 57 | + |
| 58 | + $this->assertCurrency($value->currency); |
| 59 | + |
| 60 | + return $value->amount; |
| 61 | + } |
| 62 | + |
| 63 | + private function resolveAmount(mixed $amount): int |
| 64 | + { |
| 65 | + if (is_int($amount)) { |
| 66 | + return $amount; |
| 67 | + } |
| 68 | + |
| 69 | + if (is_string($amount)) { |
| 70 | + return $this->parseDecimalString($amount); |
| 71 | + } |
| 72 | + |
| 73 | + throw new InvalidArgumentException( |
| 74 | + 'MoneyCast amount must be an int (minor units) or a numeric decimal string, got '.get_debug_type($amount).'.', |
| 75 | + ); |
| 76 | + } |
| 77 | + |
| 78 | + /** |
| 79 | + * Parses without ever going through float, so amounts like "1.005" |
| 80 | + * round deterministically instead of depending on binary float |
| 81 | + * representation (float gives 100 for "1.005" but 201 for "2.005", |
| 82 | + * despite both being an equally "exact" half-cent). |
| 83 | + */ |
| 84 | + private function parseDecimalString(string $amount): int |
| 85 | + { |
| 86 | + $amount = trim($amount); |
| 87 | + |
| 88 | + if (! preg_match('/^[+-]?(?:\d+\.?\d*|\.\d+)$/', $amount)) { |
| 89 | + throw new InvalidArgumentException("\"{$amount}\" is not a valid decimal amount."); |
| 90 | + } |
| 91 | + |
| 92 | + $negative = $amount[0] === '-'; |
| 93 | + $amount = ltrim($amount, '+-'); |
| 94 | + |
| 95 | + [$whole, $fraction] = array_pad(explode('.', $amount, 2), 2, ''); |
| 96 | + |
| 97 | + if (strlen($fraction) > $this->decimals) { |
| 98 | + $roundUp = $fraction[$this->decimals] >= '5'; |
| 99 | + $fraction = substr($fraction, 0, $this->decimals); |
| 100 | + } else { |
| 101 | + $roundUp = false; |
| 102 | + $fraction = str_pad($fraction, $this->decimals, '0'); |
| 103 | + } |
| 104 | + |
| 105 | + $minorUnits = (int) ($whole.$fraction) + ($roundUp ? 1 : 0); |
| 106 | + |
| 107 | + return $negative ? -$minorUnits : $minorUnits; |
| 108 | + } |
| 109 | + |
| 110 | + private function assertCurrency(string $currency): void |
| 111 | + { |
| 112 | + if ($currency !== $this->currency) { |
| 113 | + throw new InvalidArgumentException( |
| 114 | + "Expected currency \"{$this->currency}\", got \"{$currency}\".", |
| 115 | + ); |
| 116 | + } |
| 117 | + } |
| 118 | +} |
0 commit comments