1
|
|
|
<?php |
2
|
|
|
namespace antonienko\MoneyFormatter; |
3
|
|
|
|
4
|
|
|
use Alcohol\ISO4217; |
5
|
|
|
use Money\Currency; |
6
|
|
|
use Money\Money; |
7
|
|
|
|
8
|
|
|
class MoneyFormatter |
9
|
|
|
{ |
10
|
|
|
protected $iso4217; |
11
|
|
|
protected $locale; |
12
|
|
|
|
13
|
|
|
const SYMBOL_POSITION_LEFT = 0; |
14
|
|
|
|
15
|
|
|
const SYMBOL_POSITION_RIGHT = 1; |
16
|
|
|
|
17
|
31 |
|
public function __construct($locale) |
18
|
|
|
{ |
19
|
31 |
|
$this->iso4217 = new ISO4217(); |
20
|
31 |
|
$this->locale = $locale; |
21
|
31 |
|
} |
22
|
|
|
|
23
|
31 |
|
public function toFloat(Money $money) |
24
|
|
|
{ |
25
|
31 |
|
$iso = $this->iso4217->getByAlpha3($money->getCurrency()->getCode()); |
26
|
31 |
|
$decimals = $iso['exp']; |
27
|
31 |
|
$dividend = pow(10, $decimals); |
28
|
31 |
|
return $money->getAmount() / $dividend; |
29
|
|
|
} |
30
|
|
|
|
31
|
25 |
|
public function toString(Money $money) |
32
|
|
|
{ |
33
|
25 |
|
$number_formatter = new \NumberFormatter($this->locale, \NumberFormatter::CURRENCY); |
34
|
25 |
|
return $number_formatter->formatCurrency($this->toFloat($money), $money->getCurrency()->getCode()); |
35
|
|
|
} |
36
|
|
|
|
37
|
22 |
|
public function toSymbol(Money $money, $justSymbol = true) |
38
|
|
|
{ |
39
|
22 |
|
$string = $this->toString($money); |
40
|
22 |
|
$symbol = preg_replace('/[0-9., ]*/iu', '', $string); |
41
|
22 |
|
if ($justSymbol) { |
42
|
12 |
|
$symbol_tmp = preg_replace('/[a-z]+/iu', '', $symbol); |
43
|
12 |
|
if ('' != $symbol_tmp) { |
44
|
11 |
|
$symbol = $symbol_tmp; |
45
|
11 |
|
} |
46
|
12 |
|
} |
47
|
22 |
|
return $symbol; |
48
|
|
|
} |
49
|
|
|
|
50
|
9 |
|
public function toSymbolFromCurrency(Currency $currency, $justSymbol = true) |
51
|
|
|
{ |
52
|
9 |
|
return $this->toSymbol(new Money(1, $currency), $justSymbol); |
53
|
|
|
} |
54
|
|
|
|
55
|
3 |
|
public function getSymbolPosition(Currency $currency) |
56
|
|
|
{ |
57
|
3 |
|
$money = new Money(1, $currency); |
58
|
3 |
|
$number_formatter = $this->toString($money); |
59
|
3 |
|
$symbol = $this->toSymbol($money); |
60
|
|
|
|
61
|
3 |
|
if (strpos($number_formatter, $symbol) === 0) { |
62
|
1 |
|
return self::SYMBOL_POSITION_LEFT; |
63
|
|
|
} |
64
|
|
|
|
65
|
2 |
|
if (strpos($number_formatter, $symbol) === mb_strlen($number_formatter, 'UTF-8')) { |
66
|
2 |
|
return self::SYMBOL_POSITION_RIGHT; |
67
|
|
|
} |
68
|
|
|
throw new \Exception('Symbol position not found'); |
69
|
|
|
|
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
} |
73
|
|
|
|