AggregateCurrencies.php
1 year ago
BitcoinCurrencies.php
1 year ago
CachedCurrencies.php
1 year ago
CurrencyList.php
1 year ago
ISOCurrencies.php
1 year ago
CurrencyList.php
74 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Money\Currencies; |
| 4 | |
| 5 | use Money\Currencies; |
| 6 | use Money\Currency; |
| 7 | use Money\Exception\UnknownCurrencyException; |
| 8 | |
| 9 | /** |
| 10 | * A list of custom currencies. |
| 11 | * |
| 12 | * @author George Mponos <gmponos@gmail.com> |
| 13 | */ |
| 14 | final class CurrencyList implements Currencies |
| 15 | { |
| 16 | /** |
| 17 | * Map of currencies indexed by code. |
| 18 | * |
| 19 | * @var array |
| 20 | */ |
| 21 | private $currencies; |
| 22 | |
| 23 | public function __construct(array $currencies) |
| 24 | { |
| 25 | foreach ($currencies as $currencyCode => $subunit) { |
| 26 | if (empty($currencyCode) || !is_string($currencyCode)) { |
| 27 | throw new \InvalidArgumentException(sprintf('Currency code must be a string and not empty. "%s" given', $currencyCode)); |
| 28 | } |
| 29 | |
| 30 | if (!is_int($subunit) || $subunit < 0) { |
| 31 | throw new \InvalidArgumentException(sprintf('Currency %s does not have a valid minor unit. Must be a positive integer.', $currencyCode)); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | $this->currencies = $currencies; |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * {@inheritdoc} |
| 40 | */ |
| 41 | public function contains(Currency $currency) |
| 42 | { |
| 43 | return isset($this->currencies[$currency->getCode()]); |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * {@inheritdoc} |
| 48 | */ |
| 49 | public function subunitFor(Currency $currency) |
| 50 | { |
| 51 | if (!$this->contains($currency)) { |
| 52 | throw new UnknownCurrencyException('Cannot find currency '.$currency->getCode()); |
| 53 | } |
| 54 | |
| 55 | return $this->currencies[$currency->getCode()]; |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * {@inheritdoc} |
| 60 | */ |
| 61 | #[\ReturnTypeWillChange] |
| 62 | public function getIterator() |
| 63 | { |
| 64 | return new \ArrayIterator( |
| 65 | array_map( |
| 66 | function ($code) { |
| 67 | return new Currency($code); |
| 68 | }, |
| 69 | array_keys($this->currencies) |
| 70 | ) |
| 71 | ); |
| 72 | } |
| 73 | } |
| 74 |