| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Services\Payment; |
| 4 |
|
| 5 |
/** |
| 6 |
* Parses monetary strings from form field configuration into floats. |
| 7 |
*/ |
| 8 |
final class MoneyParser |
| 9 |
{ |
| 10 |
public static function parseToFloat(string $raw): float |
| 11 |
{ |
| 12 |
$trimmed = trim(str_replace(' ', '', $raw)); |
| 13 |
if ($trimmed === '') { |
| 14 |
return 0.0; |
| 15 |
} |
| 16 |
|
| 17 |
$cleaned = preg_replace('/[^\d.,]/', '', $trimmed) ?? ''; |
| 18 |
$cleaned = rtrim($cleaned, '.,'); |
| 19 |
if ($cleaned === '' || $cleaned === '.' || $cleaned === ',') { |
| 20 |
return 0.0; |
| 21 |
} |
| 22 |
|
| 23 |
return self::parseCleanedAmount($cleaned); |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* @param mixed $raw |
| 28 |
*/ |
| 29 |
public static function parseQuantity($raw): int |
| 30 |
{ |
| 31 |
if ($raw === null || $raw === '') { |
| 32 |
return 0; |
| 33 |
} |
| 34 |
|
| 35 |
$numeric = is_numeric($raw) ? (float) $raw : (float) trim((string) $raw); |
| 36 |
|
| 37 |
if (!is_finite($numeric)) { |
| 38 |
return 0; |
| 39 |
} |
| 40 |
|
| 41 |
return (int) floor($numeric); |
| 42 |
} |
| 43 |
|
| 44 |
private static function parseCleanedAmount(string $cleaned): float |
| 45 |
{ |
| 46 |
$lastComma = strrpos($cleaned, ','); |
| 47 |
$lastDot = strrpos($cleaned, '.'); |
| 48 |
$decIndex = max($lastComma === false ? -1 : $lastComma, $lastDot === false ? -1 : $lastDot); |
| 49 |
|
| 50 |
if ($decIndex === -1) { |
| 51 |
$digits = preg_replace('/[^\d]/', '', $cleaned) ?? '0'; |
| 52 |
$amount = (float) $digits; |
| 53 |
|
| 54 |
return is_finite($amount) ? $amount : 0.0; |
| 55 |
} |
| 56 |
|
| 57 |
$intPart = substr($cleaned, 0, $decIndex); |
| 58 |
$fracPart = preg_replace('/[^\d]/', '', substr($cleaned, $decIndex + 1)) ?? ''; |
| 59 |
$intDigits = preg_replace('/[^\d]/', '', $intPart) ?? '0'; |
| 60 |
$normalized = $fracPart !== '' ? $intDigits . '.' . $fracPart : $intDigits; |
| 61 |
$amount = (float) $normalized; |
| 62 |
|
| 63 |
return is_finite($amount) ? $amount : 0.0; |
| 64 |
} |
| 65 |
} |
| 66 |
|