You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace App\Casts;
  3. use App\Enums\NumberFormat;
  4. use App\Models\Setting\Localization;
  5. use App\Utilities\Currency\CurrencyAccessor;
  6. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  7. use Illuminate\Database\Eloquent\Model;
  8. class RateCast implements CastsAttributes
  9. {
  10. private const PRECISION = 4;
  11. public function get($model, string $key, $value, array $attributes): string
  12. {
  13. $currency_code = $this->getDefaultCurrencyCode();
  14. $computation = $attributes['computation'] ?? null;
  15. if ($computation === 'fixed') {
  16. return money($value, $currency_code)->formatSimple();
  17. }
  18. $floatValue = $value / (10 ** self::PRECISION);
  19. $format = Localization::firstOrFail()->number_format->value;
  20. [$decimal_mark, $thousands_separator] = NumberFormat::from($format)->getFormattingParameters();
  21. return $this->formatWithoutTrailingZeros($floatValue, $decimal_mark, $thousands_separator);
  22. }
  23. public function set(Model $model, string $key, mixed $value, array $attributes): int
  24. {
  25. if (is_int($value)) {
  26. return $value;
  27. }
  28. $computation = $attributes['computation'] ?? null;
  29. $currency_code = $this->getDefaultCurrencyCode();
  30. if ($computation === 'fixed') {
  31. return money($value, $currency_code, true)->getAmount();
  32. }
  33. $format = Localization::firstOrFail()->number_format->value;
  34. [$decimal_mark, $thousands_separator] = NumberFormat::from($format)->getFormattingParameters();
  35. $intValue = str_replace([$thousands_separator, $decimal_mark], ['', '.'], $value);
  36. return (int) round((float) $intValue * (10 ** self::PRECISION));
  37. }
  38. private function getDefaultCurrencyCode(): string
  39. {
  40. return CurrencyAccessor::getDefaultCurrency();
  41. }
  42. private function formatWithoutTrailingZeros($floatValue, $decimal_mark, $thousands_separator): string
  43. {
  44. $formatted = number_format($floatValue, self::PRECISION, $decimal_mark, $thousands_separator);
  45. $formatted = rtrim($formatted, '0');
  46. return rtrim($formatted, $decimal_mark);
  47. }
  48. }