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.

CurrencyConverter.php 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Utilities\Currency;
  3. use App\Facades\Forex;
  4. use Filament\Forms\Set;
  5. class CurrencyConverter
  6. {
  7. public static function convertAndSet($newCurrency, $oldCurrency, $amount): ?string
  8. {
  9. if ($newCurrency === null || $oldCurrency === $newCurrency) {
  10. return null;
  11. }
  12. $old_attr = currency($oldCurrency);
  13. $new_attr = currency($newCurrency);
  14. $temp_amount = str_replace([$old_attr->getThousandsSeparator(), $old_attr->getDecimalMark()], ['', '.'], $amount);
  15. return number_format((float) $temp_amount, $new_attr->getPrecision(), $new_attr->getDecimalMark(), $new_attr->getThousandsSeparator());
  16. }
  17. public static function convertBalance(int $amount, string $oldCurrency, string $newCurrency): int
  18. {
  19. return money($amount, $oldCurrency)->swapAmountFor($newCurrency);
  20. }
  21. public static function prepareForMutator(int $amount, string $currency): string
  22. {
  23. return money($amount, $currency)->formatSimple();
  24. }
  25. public static function prepareForAccessor(string $amount, string $currency): int
  26. {
  27. return money($amount, $currency, true)->getAmount();
  28. }
  29. public static function convertToCents(string | float $amount, ?string $currency = null): int
  30. {
  31. $currency ??= CurrencyAccessor::getDefaultCurrency();
  32. return money($amount, $currency, true)->getAmount();
  33. }
  34. public static function formatCentsToMoney(int $amount, ?string $currency = null): string
  35. {
  36. $currency ??= CurrencyAccessor::getDefaultCurrency();
  37. return money($amount, $currency)->format();
  38. }
  39. public static function formatToMoney(string | float $amount, ?string $currency = null): string
  40. {
  41. $currency ??= CurrencyAccessor::getDefaultCurrency();
  42. return money($amount, $currency, true)->format();
  43. }
  44. public static function convertCentsToFloat(int $amount, ?string $currency = null): float
  45. {
  46. $currency ??= CurrencyAccessor::getDefaultCurrency();
  47. return money($amount, $currency)->getValue();
  48. }
  49. public static function handleCurrencyChange(Set $set, $state): void
  50. {
  51. $currency = currency($state);
  52. $defaultCurrencyCode = CurrencyAccessor::getDefaultCurrency();
  53. $forexEnabled = Forex::isEnabled();
  54. $exchangeRate = $forexEnabled ? Forex::getCachedExchangeRate($defaultCurrencyCode, $state) : null;
  55. $set('name', $currency->getName() ?? '');
  56. if ($forexEnabled && $exchangeRate !== null) {
  57. $set('rate', $exchangeRate);
  58. }
  59. }
  60. }