| 1 |
<?php |
| 2 |
|
| 3 |
namespace Money\Formatter; |
| 4 |
|
| 5 |
use Money\Exception\FormatterException; |
| 6 |
use Money\Money; |
| 7 |
use Money\MoneyFormatter; |
| 8 |
|
| 9 |
/** |
| 10 |
* Formats a Money object using other Money formatters. |
| 11 |
* |
| 12 |
* @author Frederik Bosch <f.bosch@genkgo.nl> |
| 13 |
*/ |
| 14 |
final class AggregateMoneyFormatter implements MoneyFormatter |
| 15 |
{ |
| 16 |
/** |
| 17 |
* @var MoneyFormatter[] |
| 18 |
*/ |
| 19 |
private $formatters = []; |
| 20 |
|
| 21 |
/** |
| 22 |
* @param MoneyFormatter[] $formatters |
| 23 |
*/ |
| 24 |
public function __construct(array $formatters) |
| 25 |
{ |
| 26 |
if (empty($formatters)) { |
| 27 |
throw new \InvalidArgumentException(sprintf('Initialize an empty %s is not possible', self::class)); |
| 28 |
} |
| 29 |
|
| 30 |
foreach ($formatters as $currencyCode => $formatter) { |
| 31 |
if (false === $formatter instanceof MoneyFormatter) { |
| 32 |
throw new \InvalidArgumentException('All formatters must implement '.MoneyFormatter::class); |
| 33 |
} |
| 34 |
|
| 35 |
$this->formatters[$currencyCode] = $formatter; |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* {@inheritdoc} |
| 41 |
*/ |
| 42 |
public function format(Money $money) |
| 43 |
{ |
| 44 |
$currencyCode = $money->getCurrency()->getCode(); |
| 45 |
|
| 46 |
if (isset($this->formatters[$currencyCode])) { |
| 47 |
return $this->formatters[$currencyCode]->format($money); |
| 48 |
} |
| 49 |
|
| 50 |
if (isset($this->formatters['*'])) { |
| 51 |
return $this->formatters['*']->format($money); |
| 52 |
} |
| 53 |
|
| 54 |
throw new FormatterException('No formatter found for currency '.$currencyCode); |
| 55 |
} |
| 56 |
} |
| 57 |
|