AggregateMoneyParser.php
4 years ago
BitcoinMoneyParser.php
4 years ago
DecimalMoneyParser.php
1 year ago
IntlLocalizedDecimalParser.php
1 year ago
IntlMoneyParser.php
1 year ago
AggregateMoneyParser.php
59 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Money\Parser; |
| 4 | |
| 5 | use Money\Currency; |
| 6 | use Money\Exception; |
| 7 | use Money\MoneyParser; |
| 8 | |
| 9 | /** |
| 10 | * Parses a string into a Money object using other parsers. |
| 11 | * |
| 12 | * @author Frederik Bosch <f.bosch@genkgo.nl> |
| 13 | */ |
| 14 | final class AggregateMoneyParser implements MoneyParser |
| 15 | { |
| 16 | /** |
| 17 | * @var MoneyParser[] |
| 18 | */ |
| 19 | private $parsers = []; |
| 20 | |
| 21 | /** |
| 22 | * @param MoneyParser[] $parsers |
| 23 | */ |
| 24 | public function __construct(array $parsers) |
| 25 | { |
| 26 | if (empty($parsers)) { |
| 27 | throw new \InvalidArgumentException(sprintf('Initialize an empty %s is not possible', self::class)); |
| 28 | } |
| 29 | |
| 30 | foreach ($parsers as $parser) { |
| 31 | if (false === $parser instanceof MoneyParser) { |
| 32 | throw new \InvalidArgumentException('All parsers must implement '.MoneyParser::class); |
| 33 | } |
| 34 | |
| 35 | $this->parsers[] = $parser; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * {@inheritdoc} |
| 41 | */ |
| 42 | public function parse($money, $forceCurrency = null) |
| 43 | { |
| 44 | if ($forceCurrency !== null && !$forceCurrency instanceof Currency) { |
| 45 | @trigger_error('Passing a currency as string is deprecated since 3.1 and will be removed in 4.0. Please pass a '.Currency::class.' instance instead.', E_USER_DEPRECATED); |
| 46 | $forceCurrency = new Currency($forceCurrency); |
| 47 | } |
| 48 | |
| 49 | foreach ($this->parsers as $parser) { |
| 50 | try { |
| 51 | return $parser->parse($money, $forceCurrency); |
| 52 | } catch (Exception\ParserException $e) { |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | throw new Exception\ParserException(sprintf('Unable to parse %s', $money)); |
| 57 | } |
| 58 | } |
| 59 |