| 1 |
<?php |
| 2 |
|
| 3 |
namespace Money\Formatter; |
| 4 |
|
| 5 |
use Money\Currencies; |
| 6 |
use Money\Money; |
| 7 |
use Money\MoneyFormatter; |
| 8 |
|
| 9 |
/** |
| 10 |
* Formats a Money object as a decimal string. |
| 11 |
* |
| 12 |
* @author Teoh Han Hui <teohhanhui@gmail.com> |
| 13 |
*/ |
| 14 |
final class DecimalMoneyFormatter implements MoneyFormatter |
| 15 |
{ |
| 16 |
/** |
| 17 |
* @var Currencies |
| 18 |
*/ |
| 19 |
private $currencies; |
| 20 |
|
| 21 |
public function __construct(Currencies $currencies) |
| 22 |
{ |
| 23 |
$this->currencies = $currencies; |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* {@inheritdoc} |
| 28 |
*/ |
| 29 |
public function format(Money $money) |
| 30 |
{ |
| 31 |
$valueBase = $money->getAmount(); |
| 32 |
$negative = false; |
| 33 |
|
| 34 |
if ($valueBase[0] === '-') { |
| 35 |
$negative = true; |
| 36 |
$valueBase = substr($valueBase, 1); |
| 37 |
} |
| 38 |
|
| 39 |
$subunit = $this->currencies->subunitFor($money->getCurrency()); |
| 40 |
$valueLength = strlen($valueBase); |
| 41 |
|
| 42 |
if ($valueLength > $subunit) { |
| 43 |
$formatted = substr($valueBase, 0, $valueLength - $subunit); |
| 44 |
$decimalDigits = substr($valueBase, $valueLength - $subunit); |
| 45 |
|
| 46 |
if (strlen($decimalDigits) > 0) { |
| 47 |
$formatted .= '.'.$decimalDigits; |
| 48 |
} |
| 49 |
} else { |
| 50 |
$formatted = '0.'.str_pad('', $subunit - $valueLength, '0').$valueBase; |
| 51 |
} |
| 52 |
|
| 53 |
if ($negative === true) { |
| 54 |
$formatted = '-'.$formatted; |
| 55 |
} |
| 56 |
|
| 57 |
return $formatted; |
| 58 |
} |
| 59 |
} |
| 60 |
|