Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ConfigureCurrencies.php 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Utilities\Currency;
  3. use Akaunting\Money\Currency as CurrencyBase;
  4. use App\Models\Setting\Currency as CurrencyModel;
  5. use Illuminate\Database\Eloquent\Collection;
  6. use Symfony\Component\Intl\Currencies;
  7. use Symfony\Component\Intl\Exception\MissingResourceException;
  8. class ConfigureCurrencies
  9. {
  10. public static function syncCurrencies(): void
  11. {
  12. $currencies = static::fetchCurrencies();
  13. if ($currencies->isEmpty()) {
  14. return;
  15. }
  16. $customCurrencies = static::formatCurrencies($currencies);
  17. static::mergeAndSetCurrencies($customCurrencies);
  18. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  19. if ($defaultCurrency) {
  20. config(['money.defaults.currency' => $defaultCurrency]);
  21. }
  22. }
  23. protected static function fetchCurrencies(): Collection
  24. {
  25. return CurrencyModel::all();
  26. }
  27. protected static function formatCurrencies(Collection $currencies): array
  28. {
  29. $customCurrencies = [];
  30. foreach ($currencies as $currency) {
  31. /** @var CurrencyModel $currency */
  32. $customCurrencies[$currency->code] = [
  33. 'name' => $currency->name,
  34. 'rate' => $currency->rate,
  35. 'precision' => $currency->precision,
  36. 'symbol' => $currency->symbol,
  37. 'symbol_first' => $currency->symbol_first,
  38. 'decimal_mark' => $currency->decimal_mark,
  39. 'thousands_separator' => $currency->thousands_separator,
  40. ];
  41. }
  42. return $customCurrencies;
  43. }
  44. protected static function mergeAndSetCurrencies(array $customCurrencies): void
  45. {
  46. $existingCurrencies = CurrencyBase::getCurrencies();
  47. foreach ($existingCurrencies as $code => $currency) {
  48. try {
  49. $name = Currencies::getName($code, app()->getLocale());
  50. $existingCurrencies[$code]['name'] = ucwords($name);
  51. } catch (MissingResourceException) {
  52. $existingCurrencies[$code]['name'] = $currency['name'];
  53. }
  54. }
  55. $mergedCurrencies = array_replace_recursive($existingCurrencies, $customCurrencies);
  56. CurrencyBase::setCurrencies($mergedCurrencies);
  57. }
  58. }