Skip to content

Commit ec26e88

Browse files
committed
Add CurrencyDisplay modes to MoneyLocaleFormatter
1 parent 153ed13 commit ec26e88

8 files changed

Lines changed: 486 additions & 75 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,16 @@
88
- `ExchangeRateProviderException`
99
- `MoneyFormatException`
1010
- `MoneyNumberFormatter` has been removed; call `NumberFormatter::formatCurrency()` directly instead
11+
- `Money::formatToLocale()` and `MoneyLocaleFormatter` now format through ICU's modern number skeleton pipeline, and minor formatting differences may appear in some locales
12+
- `Money::formatToLocale()` and `MoneyLocaleFormatter` now require the intl extension to be linked against **ICU 62.1 or later**, and throw a `MoneyFormatException` on older ICU (this is independent of the PHP version)
13+
- `Money::formatToLocale()` and `MoneyLocaleFormatter` now accept a `CurrencyDisplay` parameter in the second position
1114
- `Money::formatToLocale()` and `MoneyLocaleFormatter` now throw a `MoneyFormatException` if the amount cannot be accurately represented as a float, rather than formatting it with wrong digits
1215

16+
✨ **New features**
17+
18+
- `Money::formatToLocale()` and `MoneyLocaleFormatter` now accept a `CurrencyDisplay` parameter controlling how the currency is displayed: `Symbol` (default), `NarrowSymbol`, `Code`, `Name`, or `None` (amount only)
19+
- `MoneyLocaleFormatter` now properly displays custom currencies whose code is not three letters (e.g. `USDT`, `GOLD`)
20+
1321
## [0.14.2](https://github.com/brick/money/releases/tag/0.14.2) - 2026-08-28
1422

1523
📌 **Compatibility**

‎README.md‎

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -647,7 +647,8 @@ $money = Money::of('0.123', $bitcoin); // XBT 0.12300000
647647
648648
## Formatting
649649

650-
**Formatting requires the [intl extension](http://php.net/manual/en/book.intl.php).**
650+
> [!IMPORTANT]
651+
> Formatting requires the [intl extension](http://php.net/manual/en/book.intl.php), linked against ICU 62.1 or later.
651652
652653
Money objects can be formatted according to a given locale:
653654

@@ -657,8 +658,48 @@ echo $money->formatToLocale('en_US'); // $5,000.00
657658
echo $money->formatToLocale('fr_FR'); // 5 000,00 $US
658659
```
659660

660-
> [!NOTE]
661-
> Formatting is performed using intl's `NumberFormatter`, which represents values using floats. If the amount cannot be accurately represented as a float, a `MoneyFormatException` is thrown rather than formatting it with wrong digits.
661+
The optional `$currencyDisplay` parameter controls how the currency is rendered:
662+
663+
```php
664+
use Brick\Money\CurrencyDisplay;
665+
666+
$money = Money::of(5000, 'USD');
667+
echo $money->formatToLocale('en_US', CurrencyDisplay::Symbol); // $5,000.00
668+
echo $money->formatToLocale('en_US', CurrencyDisplay::NarrowSymbol); // $5,000.00
669+
echo $money->formatToLocale('en_US', CurrencyDisplay::Code); // USD 5,000.00
670+
echo $money->formatToLocale('en_US', CurrencyDisplay::Name); // 5,000.00 US dollars
671+
echo $money->formatToLocale('en_US', CurrencyDisplay::None); // 5,000.00
672+
```
673+
674+
`Symbol` uses the symbol the locale considers appropriate, disambiguating a foreign currency where needed;
675+
`NarrowSymbol` always uses the bare glyph. They differ only in that case:
676+
677+
```php
678+
$money = Money::of(5000, 'USD');
679+
echo $money->formatToLocale('en_CA', CurrencyDisplay::Symbol); // US$5,000.00
680+
echo $money->formatToLocale('en_CA', CurrencyDisplay::NarrowSymbol); // $5,000.00
681+
```
682+
683+
A [custom currency](#custom-currencies) displays its code in every mode, placed and spaced the way the locale displays
684+
any currency it has no symbol or name for:
685+
686+
```php
687+
$money = Money::of(5000, new Currency('USDT', null, 'Tether', 2));
688+
echo $money->formatToLocale('en_US'); // USDT 5,000.00
689+
echo $money->formatToLocale('fr_FR'); // 5 000,00 USDT
690+
echo $money->formatToLocale('en_US', CurrencyDisplay::Name); // 5,000.00 USDT
691+
echo $money->formatToLocale('en_US', CurrencyDisplay::None); // 5,000.00
692+
```
693+
694+
The optional `$allowWholeNumber` parameter drops the fraction digits when the amount has no fraction:
695+
696+
```php
697+
$money = Money::of(5000, 'USD');
698+
echo $money->formatToLocale('en_US', CurrencyDisplay::Symbol, true); // $5,000
699+
700+
$money = Money::of('5000.50', 'USD');
701+
echo $money->formatToLocale('en_US', CurrencyDisplay::Symbol, true); // $5,000.50
702+
```
662703

663704
## Storing Money objects in a database
664705

‎composer.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
"phpunit/phpunit": "^11.0"
2222
},
2323
"suggest": {
24-
"ext-intl": "Required to format Money objects"
24+
"ext-intl": "Required to format Money objects to a locale (needs ICU 62.1 or later)"
2525
},
2626
"autoload": {
2727
"psr-4": {

‎src/CurrencyDisplay.php‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Brick\Money;
6+
7+
/**
8+
* Determines how the currency is displayed when formatting a Money to a locale.
9+
*/
10+
enum CurrencyDisplay
11+
{
12+
/**
13+
* The currency symbol appropriate for the target locale.
14+
*
15+
* The symbol is disambiguated for the locale's audience; for example, `USD 1234.56` formats as:
16+
*
17+
* - en_US: `$1,234.56`
18+
* - en_CA: `US$1,234.56`
19+
*
20+
* A currency the locale has no symbol for, including any custom currency, displays its code instead:
21+
*
22+
* - en_US: `USDT 1,234.56`
23+
* - fr_FR: `1 234,56 USDT`
24+
*/
25+
case Symbol;
26+
27+
/**
28+
* The narrow currency symbol: the bare glyph, without the disambiguation the locale would otherwise add.
29+
*
30+
* Identical to `Symbol` unless the locale would add letters to the glyph, such as `US$` for `$`, or
31+
* replace it with the code; for example, `USD 1234.56` formats as:
32+
*
33+
* - en_US: `$1,234.56`
34+
* - en_CA: `$1,234.56`
35+
*/
36+
case NarrowSymbol;
37+
38+
/**
39+
* The currency code.
40+
*
41+
* For example, `USD 1234.56` formats as:
42+
*
43+
* - en_US: `USD 1,234.56`
44+
* - fr_FR: `1 234,56 USD`
45+
*/
46+
case Code;
47+
48+
/**
49+
* The currency display name, pluralized according to the formatted amount.
50+
*
51+
* For example, `USD 1234.56` formats as:
52+
*
53+
* - en_US: `1,234.56 US dollars`
54+
* - fr_FR: `1 234,56 dollars des États-Unis`
55+
*
56+
* A custom currency displays its code, not the name it was constructed with:
57+
*
58+
* - en_US: `1,234.56 USDT`
59+
* - fr_FR: `1 234,56 USDT`
60+
*/
61+
case Name;
62+
63+
/**
64+
* No currency indicator: the amount only.
65+
*
66+
* For example, `USD 1234.56` formats as:
67+
*
68+
* - en_US: `1,234.56`
69+
* - fr_FR: `1 234,56`
70+
*
71+
* The amount is still rendered using the locale's monetary number format (some locales format monetary amounts
72+
* differently from plain numbers, e.g. fr_CH uses `1 234 567.89` for money but `1 234 567,89` for plain numbers).
73+
*/
74+
case None;
75+
}

‎src/Formatter/MoneyLocaleFormatter.php‎

Lines changed: 151 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,46 +5,82 @@
55
namespace Brick\Money\Formatter;
66

77
use Brick\Math\BigDecimal;
8+
use Brick\Money\CurrencyDisplay;
89
use Brick\Money\Exception\MoneyFormatException;
910
use Brick\Money\Money;
1011
use Brick\Money\MoneyFormatter;
11-
use NumberFormatter;
12+
use IntlException;
13+
use MessageFormatter;
1214
use Override;
1315

1416
use function extension_loaded;
1517
use function floor;
16-
use function intl_get_error_message;
1718
use function log10;
19+
use function preg_last_error_msg;
20+
use function preg_match;
21+
use function preg_replace;
1822
use function sprintf;
23+
use function str_contains;
24+
use function str_repeat;
25+
use function str_replace;
26+
use function strtoupper;
27+
use function version_compare;
1928

29+
use const INTL_ICU_VERSION;
2030
use const PHP_FLOAT_DIG;
2131
use const PHP_FLOAT_MIN;
2232

2333
/**
24-
* Note that this formatter uses intl's NumberFormatter internally, which represents values using floats. If the amount
25-
* cannot be accurately represented as a float, a MoneyFormatException is thrown rather than formatting it with wrong
26-
* digits.
34+
* Formats a Money to a locale.
35+
*
36+
* This formatter uses intl's MessageFormatter internally, which represents values using floats. If the amount cannot be
37+
* accurately represented as a float, a MoneyFormatException is thrown rather than formatting it with wrong digits.
38+
*
39+
* This formatter requires the intl extension, linked against ICU 62 or later.
2740
*/
2841
final readonly class MoneyLocaleFormatter implements MoneyFormatter
2942
{
30-
private bool $allowWholeNumber;
43+
/**
44+
* The number skeleton syntax used here was introduced in ICU 62.
45+
*/
46+
private const MINIMUM_ICU_VERSION = '62.1';
47+
48+
/**
49+
* Stands in for a custom code (≠ 3 letters) that cannot be embedded in the skeleton.
50+
*/
51+
private const STAND_IN_CODE = 'ZZZ';
3152

32-
private NumberFormatter $numberFormatter;
53+
private string $locale;
54+
55+
private CurrencyDisplay $currencyDisplay;
56+
57+
private bool $allowWholeNumber;
3358

3459
/**
35-
* @param string $locale The locale to format to, for example 'fr_FR' or 'en_US'.
36-
* @param bool $allowWholeNumber Whether to allow formatting as a whole number if the amount has no fraction.
60+
* @param string $locale The locale to format to, for example 'fr_FR' or 'en_US'.
61+
* @param CurrencyDisplay $currencyDisplay How the currency should be displayed in the formatted output.
62+
* @param bool $allowWholeNumber Whether to allow formatting as a whole number if the amount has no fraction.
3763
*
38-
* @throws MoneyFormatException If the intl extension is not installed.
64+
* @throws MoneyFormatException If the intl extension is not installed, or the ICU version is too old.
3965
*/
40-
public function __construct(string $locale, bool $allowWholeNumber = false)
66+
public function __construct(string $locale, CurrencyDisplay $currencyDisplay = CurrencyDisplay::Symbol, bool $allowWholeNumber = false)
4167
{
4268
if (! extension_loaded('intl')) {
43-
throw new MoneyFormatException('Formatting money by locale requires the intl extension.');
69+
throw new MoneyFormatException('Formatting a Money to a locale requires the intl extension.');
4470
}
4571

72+
// @phpstan-ignore if.alwaysFalse (phpstan hardcodes a value for INTL_ICU_VERSION)
73+
if (version_compare(INTL_ICU_VERSION, self::MINIMUM_ICU_VERSION, '<')) {
74+
throw new MoneyFormatException(sprintf(
75+
'Formatting a Money to a locale requires ICU %s or later; this system provides ICU %s.',
76+
self::MINIMUM_ICU_VERSION,
77+
INTL_ICU_VERSION,
78+
));
79+
}
80+
81+
$this->locale = $locale;
82+
$this->currencyDisplay = $currencyDisplay;
4683
$this->allowWholeNumber = $allowWholeNumber;
47-
$this->numberFormatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);
4884
}
4985

5086
#[Override]
@@ -62,26 +98,119 @@ public function format(Money $money): string
6298

6399
$this->checkFloatAccuracy($amount);
64100

65-
$scale = $amount->getScale();
101+
$currencyCode = $money->getCurrency()->getCurrencyCode();
102+
$isoCode = $this->toIsoCode($currencyCode);
66103

67-
$this->numberFormatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $scale);
68-
$this->numberFormatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $scale);
104+
$skeleton = $this->buildSkeleton($amount->getScale(), $isoCode ?? self::STAND_IN_CODE);
69105

70-
$formatted = $this->numberFormatter->formatCurrency(
71-
$amount->toFloat(),
72-
$money->getCurrency()->getCurrencyCode(),
73-
);
106+
// MessageFormatter::format() throws on failure when intl.use_exceptions is on, and returns false when off
107+
try {
108+
$formatter = new MessageFormatter($this->locale, '{0, number, ::' . $skeleton . '}');
109+
$formatted = $formatter->format([$amount->toFloat()]);
110+
} catch (IntlException $e) {
111+
throw new MoneyFormatException(sprintf(
112+
'MessageFormatter failed to format the Money to locale "%s": %s',
113+
$this->locale,
114+
$e->getMessage(),
115+
), $e);
116+
}
74117

75118
if ($formatted === false) {
76119
throw new MoneyFormatException(sprintf(
77-
'NumberFormatter failed to format the given Money: %s',
78-
intl_get_error_message(),
120+
'MessageFormatter failed to format the Money to locale "%s": %s',
121+
$this->locale,
122+
$formatter->getErrorMessage(),
79123
));
80124
}
81125

126+
if ($this->currencyDisplay === CurrencyDisplay::None) {
127+
return $this->removeCurrencySpacing($formatted);
128+
}
129+
130+
if ($isoCode === null) {
131+
return $this->substituteCustomCode($formatted, $currencyCode);
132+
}
133+
82134
return $formatted;
83135
}
84136

137+
/**
138+
* Returns the currency code to embed in the skeleton, or null if the given code cannot be embedded.
139+
*
140+
* ICU only supports currency codes with 3 characters.
141+
*/
142+
private function toIsoCode(string $currencyCode): ?string
143+
{
144+
$isIsoShaped = preg_match('/^[A-Za-z]{3}$/', $currencyCode);
145+
146+
if ($isIsoShaped === false) {
147+
throw new MoneyFormatException(sprintf(
148+
'preg_match() failed to check the currency code shape: %s',
149+
preg_last_error_msg(),
150+
));
151+
}
152+
153+
return $isIsoShaped === 1 ? strtoupper($currencyCode) : null;
154+
}
155+
156+
/**
157+
* Builds the ICU number skeleton for the given scale and embeddable currency code.
158+
*/
159+
private function buildSkeleton(int $scale, string $isoCode): string
160+
{
161+
$precision = $scale === 0 ? 'precision-integer' : '.' . str_repeat('0', $scale);
162+
163+
$unitWidth = match ($this->currencyDisplay) {
164+
CurrencyDisplay::Symbol => 'unit-width-short',
165+
CurrencyDisplay::NarrowSymbol => 'unit-width-narrow',
166+
CurrencyDisplay::Code => 'unit-width-iso-code',
167+
CurrencyDisplay::Name => 'unit-width-full-name',
168+
CurrencyDisplay::None => 'unit-width-hidden',
169+
};
170+
171+
return sprintf('currency/%s %s %s', $isoCode, $precision, $unitWidth);
172+
}
173+
174+
/**
175+
* Replaces the stand-in code with the custom code in the finished output.
176+
*/
177+
private function substituteCustomCode(string $formatted, string $currencyCode): string
178+
{
179+
if (! str_contains($formatted, self::STAND_IN_CODE)) {
180+
throw new MoneyFormatException(sprintf(
181+
'The stand-in currency code %s does not appear in the formatted output "%s" on ICU %s; this is not expected on any known ICU, please report it.',
182+
self::STAND_IN_CODE,
183+
$formatted,
184+
INTL_ICU_VERSION,
185+
));
186+
}
187+
188+
return str_replace(self::STAND_IN_CODE, $currencyCode, $formatted);
189+
}
190+
191+
/**
192+
* Removes the pattern spacing left behind by CurrencyDisplay::None.
193+
*
194+
* When ICU hides the currency, it leaves behind the spaces that surrounded it in the pattern: a trailing no-break
195+
* space in fr_FR, or a space between the sign and the number in bo (Tibetan). This removes every space that does
196+
* not have a digit on both sides. Such a space can only be one of those leftovers, never a grouping separator,
197+
* since grouping separators always sit between digits. Bidi control characters are kept: in right-to-left locale
198+
* they wrap the sign and the number, and removing them would break the display.
199+
*/
200+
private function removeCurrencySpacing(string $formatted): string
201+
{
202+
$trimmed = preg_replace('/(?<!\p{N})\p{Zs}+|\p{Zs}+(?!\p{N})/u', '', $formatted);
203+
204+
if ($trimmed === null) {
205+
throw new MoneyFormatException(sprintf(
206+
'preg_replace() failed to remove the currency spacing: %s',
207+
preg_last_error_msg(),
208+
));
209+
}
210+
211+
return $trimmed;
212+
}
213+
85214
/**
86215
* Checks that the given amount can be accurately represented as a float.
87216
*

0 commit comments

Comments
 (0)