選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

CurrencyConverter.php 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 handleCurrencyChange(Set $set, $state): void
  40. {
  41. $currency = currency($state);
  42. $defaultCurrencyCode = CurrencyAccessor::getDefaultCurrency();
  43. $forexEnabled = Forex::isEnabled();
  44. $exchangeRate = $forexEnabled ? Forex::getCachedExchangeRate($defaultCurrencyCode, $state) : null;
  45. $set('name', $currency->getName() ?? '');
  46. if ($forexEnabled && $exchangeRate !== null) {
  47. $set('rate', $exchangeRate);
  48. }
  49. }
  50. }