GiveCurrencies.php
66 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Framework\Support\Currencies; |
| 4 | |
| 5 | use Money\Currencies; |
| 6 | use Money\Currency; |
| 7 | use Money\Exception\UnknownCurrencyException; |
| 8 | |
| 9 | /** |
| 10 | * Custom currencies implementation that uses GiveWP's currency list and filter. |
| 11 | * Implements the Money library's Currencies interface to ensure Money operations |
| 12 | * use GiveWP's configured currencies and decimal settings. |
| 13 | * |
| 14 | * @since 4.10.0 |
| 15 | */ |
| 16 | class GiveCurrencies implements Currencies |
| 17 | { |
| 18 | /** |
| 19 | * @since 4.10.0 |
| 20 | */ |
| 21 | public function contains(Currency $currency): bool |
| 22 | { |
| 23 | $supportedCurrencies = array_keys(give_get_currencies_list()); |
| 24 | return in_array($currency->getCode(), $supportedCurrencies, true); |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * @since 4.10.0 |
| 29 | */ |
| 30 | public function subunitFor(Currency $currency): int |
| 31 | { |
| 32 | if (!$this->contains($currency)) { |
| 33 | throw new UnknownCurrencyException('Unknown currency: ' . $currency->getCode()); |
| 34 | } |
| 35 | |
| 36 | $currencies = give_get_currencies_list(); |
| 37 | $currencyData = $currencies[$currency->getCode()] ?? []; |
| 38 | $decimals = $currencyData['setting']['number_decimals'] ?? 2; |
| 39 | |
| 40 | return (int) $decimals; |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Returns an iterator over all supported currencies. |
| 45 | * |
| 46 | * Uses yield (Generator) instead of ArrayIterator for better performance and memory efficiency: |
| 47 | * - Lazy loading: Creates Currency objects only when needed during iteration |
| 48 | * - Memory efficient: Doesn't load all 100+ Currency objects into memory at once |
| 49 | * - Dynamic data: Based on give_get_currencies_list() which can change via filters |
| 50 | * - Better performance: Especially important for large currency lists (100+ currencies) |
| 51 | * |
| 52 | * This approach is more suitable than ArrayIterator (used by BitcoinCurrencies/ISOCurrencies) |
| 53 | * because GiveWP's currency list is dynamic and potentially large, unlike static ISO lists. |
| 54 | * |
| 55 | * @since 4.10.0 |
| 56 | */ |
| 57 | public function getIterator(): \Traversable |
| 58 | { |
| 59 | $supportedCurrencies = array_keys(give_get_currencies_list()); |
| 60 | |
| 61 | foreach ($supportedCurrencies as $currencyCode) { |
| 62 | yield new Currency($currencyCode); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 |