PromotionAmountFormatter.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. namespace App\Support;
  3. /** Presentation only. Accounting and eligibility keep their original decimal precision. */
  4. final class PromotionAmountFormatter
  5. {
  6. private const MONEY_FIELDS = ['amount', 'required_flow', 'balance', 'available_balance', 'frozen_balance',
  7. 'before_balance', 'after_balance', 'budget', 'budget_used', 'deposit_min', 'deposit_max', 'deposit_total',
  8. 'loss_amount', 'reward_amount', 'min_deposit', 'min_effective_bet', 'deposit_amount', 'team_deposit_amount',
  9. 'bet_amount', 'team_bet_amount', 'loss', 'coins', 'remaining'];
  10. private const MONEY_TASKS = ['deposit', 'team_deposit', 'bet', 'team_bet'];
  11. public static function amount($value)
  12. {
  13. if ((!is_string($value) && !is_int($value) && !is_float($value))
  14. || !preg_match('/^-?\d+(?:\.\d+)?$/D', (string) $value)) return $value;
  15. $fixed = bcadd((string) $value, '0', 2);
  16. if (bccomp($fixed, '0', 2) === 0) return '0';
  17. return str_ends_with($fixed, '.00') ? substr($fixed, 0, -3) : $fixed;
  18. }
  19. public static function response($value)
  20. {
  21. if ($value instanceof \JsonSerializable) $value = $value->jsonSerialize();
  22. elseif ($value instanceof \Traversable) $value = iterator_to_array($value);
  23. $object = $value instanceof \stdClass;
  24. if ($object) $value = (array) $value;
  25. if (!is_array($value)) return $value;
  26. $moneyTask = in_array($value['key'] ?? null, self::MONEY_TASKS, true);
  27. $result = [];
  28. foreach ($value as $key => $item) {
  29. $isAmount = in_array($key, self::MONEY_FIELDS, true) || ($moneyTask && in_array($key, ['value', 'target'], true));
  30. $result[$key] = $isAmount ? self::amount($item) : self::response($item);
  31. }
  32. return $object ? (object) $result : $result;
  33. }
  34. }