-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathCurrency.php
More file actions
76 lines (59 loc) · 2.41 KB
/
Currency.php
File metadata and controls
76 lines (59 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
namespace DuncanMcClean\SimpleCommerce;
use DuncanMcClean\SimpleCommerce\Exceptions\CurrencyFormatterNotWorking;
use DuncanMcClean\SimpleCommerce\Exceptions\SiteNotConfiguredException;
use Illuminate\Support\Facades\Config;
use Money\Currencies\ISOCurrencies;
use Money\Currency as MoneyCurrency;
use Money\Formatter\IntlMoneyFormatter;
use Money\Money;
use NumberFormatter;
use Statamic\Sites\Site;
class Currency
{
public static function get(Site $site): array
{
$siteSettings = collect(Config::get('simple-commerce.sites'))
->get($site->handle());
if (! $siteSettings) {
throw new SiteNotConfiguredException("Site config not found [{$site->handle()}]");
}
return Currencies::where('code', $siteSettings['currency'])
->first();
}
public static function parse($amount, Site $site): string
{
if (is_string($amount)) {
if (str_contains($amount, '.')) {
$amount = str_replace('.', '', $amount);
}
$amount = (int) $amount;
}
if (is_float($amount)) {
$amount = $amount * 100;
}
try {
$money = new Money(str_replace('.', '', (int) $amount), new MoneyCurrency(self::get($site)['code']));
$numberFormatter = new NumberFormatter($site->locale(), NumberFormatter::CURRENCY);
$currencyFormattingConfig = Config::get("simple-commerce.sites.{$site->handle()}.currency_formatting");
if (isset($currencyFormattingConfig['decimal_separator'])) {
$numberFormatter->setSymbol(NumberFormatter::MONETARY_SEPARATOR_SYMBOL, $currencyFormattingConfig['decimal_separator']);
}
if (isset($currencyFormattingConfig['thousand_separator'])) {
$numberFormatter->setSymbol(NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL, $currencyFormattingConfig['thousand_separator']);
}
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, new ISOCurrencies);
return $moneyFormatter->format($money);
} catch (\ErrorException $e) {
throw new CurrencyFormatterNotWorking('Extension PHP-intl not installed.');
}
}
public static function toPence(float $amount): int
{
return $amount * 100;
}
public static function toDecimal(int $amount): float
{
return $amount / 100;
}
}