forked from Skillshare/formatphp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberFormat.php
More file actions
615 lines (522 loc) · 19.4 KB
/
NumberFormat.php
File metadata and controls
615 lines (522 loc) · 19.4 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
<?php
/**
* This file is part of formatphp/formatphp
*
* formatphp/formatphp is open source software: you can distribute
* it and/or modify it under the terms of the MIT License
* (the "License"). You may not use this file except in
* compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* @copyright Copyright (c) Skillshare, Inc. <https://www.skillshare.com>
* @copyright Copyright (c) FormatPHP Contributors <https://formatphp.dev>
* @license https://opensource.org/licenses/MIT MIT License
*/
declare(strict_types=1);
namespace FormatPHP\Intl;
use FormatPHP\Exception\InvalidArgumentException;
use FormatPHP\Exception\UnableToFormatNumberException;
use IntlException as PhpIntlException;
use Locale as PhpLocale;
use MessageFormatter as PhpMessageFormatter;
use Throwable;
use function array_filter;
use function implode;
use function in_array;
use function is_int;
use function sprintf;
use function str_pad;
use function str_repeat;
use function strpos;
use function substr;
use function trim;
/**
* Formats a number for a given locale
*
* @phpstan-import-type FractionDigitsType from NumberFormatOptions
*/
class NumberFormat implements NumberFormatInterface
{
/**
* Prefixes compiled from the CLDR data files
*
* @link https://github.com/unicode-org/cldr/blob/main/common/validity/unit.xml
*/
private const UNIT_PREFIXES = [
'acceleration',
'angle',
'area',
'concentr',
'consumption',
'digital',
'duration',
'electric',
'energy',
'force',
'frequency',
'graphics',
'length',
'light',
'mass',
'power',
'pressure',
'speed',
'temperature',
'torque',
'volume',
];
private const SYMBOLS_ACCOUNTING_SIGN_DISPLAY = [
NumberFormatOptions::SIGN_DISPLAY_ALWAYS => 'sign-accounting-always',
NumberFormatOptions::SIGN_DISPLAY_EXCEPT_ZERO => 'sign-accounting-except-zero',
NumberFormatOptions::SIGN_DISPLAY_NEGATIVE => 'sign-accounting-negative',
];
private const SYMBOLS_COMPACT_DISPLAY = [
NumberFormatOptions::COMPACT_DISPLAY_LONG => 'compact-long',
NumberFormatOptions::COMPACT_DISPLAY_SHORT => 'compact-short',
];
private const SYMBOLS_CURRENCY_DISPLAY = [
NumberFormatOptions::CURRENCY_DISPLAY_CODE => 'unit-width-iso-code',
NumberFormatOptions::CURRENCY_DISPLAY_NAME => 'unit-width-full-name',
NumberFormatOptions::CURRENCY_DISPLAY_NARROW_SYMBOL => 'unit-width-narrow',
NumberFormatOptions::CURRENCY_DISPLAY_SYMBOL => 'unit-width-short',
];
private const SYMBOLS_ROUNDING_PRIORITY = [
NumberFormatOptions::ROUNDING_PRIORITY_LESS_PRECISION => 's',
NumberFormatOptions::ROUNDING_PRIORITY_MORE_PRECISION => 'r',
];
private const SYMBOLS_SIGN_DISPLAY = [
NumberFormatOptions::SIGN_DISPLAY_ALWAYS => 'sign-always',
NumberFormatOptions::SIGN_DISPLAY_EXCEPT_ZERO => 'sign-except-zero',
NumberFormatOptions::SIGN_DISPLAY_NEVER => 'sign-never',
NumberFormatOptions::SIGN_DISPLAY_NEGATIVE => 'sign-negative',
];
private const SYMBOLS_UNIT_WIDTH_DISPLAY_TYPE = [
NumberFormatOptions::UNIT_DISPLAY_LONG => 'unit-width-full-name',
NumberFormatOptions::UNIT_DISPLAY_NARROW => 'unit-width-narrow',
NumberFormatOptions::UNIT_DISPLAY_SHORT => 'unit-width-short',
];
private const SYMBOLS_USE_GROUPING = [
NumberFormatOptions::USE_GROUPING_ALWAYS => 'group-on-aligned',
NumberFormatOptions::USE_GROUPING_FALSE => 'group-off',
NumberFormatOptions::USE_GROUPING_MIN2 => 'group-min2',
NumberFormatOptions::USE_GROUPING_THOUSANDS => 'group-thousands',
NumberFormatOptions::USE_GROUPING_TRUE => 'group-on-aligned',
];
private const SYMBOLS_ROUNDING_MODE = [
NumberFormatOptions::ROUNDING_MODE_CEIL => 'rounding-mode-ceiling',
NumberFormatOptions::ROUNDING_MODE_FLOOR => 'rounding-mode-floor',
NumberFormatOptions::ROUNDING_MODE_EXPAND => 'rounding-mode-up',
NumberFormatOptions::ROUNDING_MODE_TRUNC => 'rounding-mode-down',
NumberFormatOptions::ROUNDING_MODE_HALF_CEIL => 'rounding-mode-half-ceiling',
NumberFormatOptions::ROUNDING_MODE_HALF_FLOOR => 'rounding-mode-half-floor',
NumberFormatOptions::ROUNDING_MODE_HALF_EXPAND => 'rounding-mode-half-up',
NumberFormatOptions::ROUNDING_MODE_HALF_TRUNC => 'rounding-mode-half-down',
NumberFormatOptions::ROUNDING_MODE_HALF_EVEN => 'rounding-mode-half-even',
NumberFormatOptions::ROUNDING_MODE_HALF_ODD => 'rounding-mode-half-odd',
NumberFormatOptions::ROUNDING_MODE_UNNECESSARY => 'rounding-mode-unnecessary',
];
private const SCI_ENG_NOTATION = [
NumberFormatOptions::NOTATION_SCIENTIFIC,
NumberFormatOptions::NOTATION_ENGINEERING,
];
private string $originalLocaleName;
private string $localeName;
private string $skeleton;
/**
* @throws InvalidArgumentException
*/
public function __construct(?LocaleInterface $locale = null, ?NumberFormatOptions $options = null)
{
$locale = $locale ?? new Locale(PhpLocale::getDefault());
$this->originalLocaleName = $locale->toString();
$options = $options ? clone $options : new NumberFormatOptions();
if ($options->numberingSystem !== null) {
$locale = $locale->withNumberingSystem($options->numberingSystem);
}
$this->localeName = $locale->toString();
$this->skeleton = $this->buildSkeleton($options);
}
/**
* @inheritDoc
*/
public function format($number): string
{
try {
return $this->doFormat($number);
} catch (Throwable $exception) {
throw new UnableToFormatNumberException(
sprintf(
'Unable to format number "%s" for locale "%s"',
$number,
$this->originalLocaleName,
),
is_int($exception->getCode()) ? $exception->getCode() : 0,
$exception,
);
}
}
/**
* Returns the number skeleton generated from the options provided
*
* @internal
*/
public function getSkeleton(): string
{
return $this->skeleton;
}
/**
* Returns the locale constructed from the date/time format options
*
* @internal
*/
public function getEvaluatedLocale(): string
{
return $this->localeName;
}
/**
* @param int | float $number
*
* @throws PhpIntlException
* @throws UnableToFormatNumberException
*/
private function doFormat($number): string
{
$pattern = "{0, number, ::$this->skeleton}";
// PHP's `NumberFormatter::setPattern()` method leaves much to be desired,
// so we will use the PHP `MessageFormatter` class, instead.
$formatter = new PhpMessageFormatter($this->localeName, $pattern);
$formattedNumber = $formatter->format([$number]);
if ($formattedNumber === false) {
throw new UnableToFormatNumberException(
$formatter->getErrorMessage(),
$formatter->getErrorCode(),
);
}
return $formattedNumber;
}
/**
* @throws InvalidArgumentException
*/
private function buildSkeleton(NumberFormatOptions $options): string
{
$skeleton = [];
$skeleton = $this->buildStyleSkeleton($skeleton, $options);
$skeleton = $this->buildNotation($skeleton, $options);
$skeleton = $this->buildUseGrouping($skeleton, $options);
$skeleton = $this->buildRoundingMode($skeleton, $options);
$skeleton = $this->buildNumberingSystem($skeleton, $options);
$skeleton = $this->buildDigits($skeleton, $options);
$skeleton = $this->buildScale($skeleton, $options);
return implode(' ', array_filter($skeleton));
}
/**
* @param string[] $skeleton
*
* @return string[]
*
* @throws InvalidArgumentException
*/
private function buildStyleSkeleton(array $skeleton, NumberFormatOptions $options): array
{
switch ($options->style) {
case NumberFormatOptions::STYLE_CURRENCY:
return $this->buildStyleCurrencySkeleton($skeleton, $options);
case NumberFormatOptions::STYLE_UNIT:
return $this->buildStyleUnitSkeleton($skeleton, $options);
case NumberFormatOptions::STYLE_PERCENT:
return $this->buildStylePercentSkeleton($skeleton, $options);
}
return $skeleton;
}
/**
* @param string[] $skeleton
*
* @return string[]
*
* @throws InvalidArgumentException
*/
private function buildStyleCurrencySkeleton(array $skeleton, NumberFormatOptions $options): array
{
if ($options->currency === null) {
throw new InvalidArgumentException('The currency property must be provided when the style is "currency"');
}
$skeleton[] = 'currency/' . $options->currency;
$skeleton[] = self::SYMBOLS_CURRENCY_DISPLAY[$options->currencyDisplay] ?? 'unit-width-short';
if ($options->currencySign === NumberFormatOptions::CURRENCY_SIGN_ACCOUNTING) {
$skeleton[] = self::SYMBOLS_ACCOUNTING_SIGN_DISPLAY[$options->signDisplay] ?? 'sign-accounting';
}
return $skeleton;
}
/**
* @param string[] $skeleton
*
* @return string[]
*
* @throws InvalidArgumentException
*/
private function buildStyleUnitSkeleton(array $skeleton, NumberFormatOptions $options): array
{
if ($options->unit === null) {
throw new InvalidArgumentException('The unit property must be provided when the style is "unit"');
}
// Determine whether to use the long skeleton or the concise skeleton,
// based on whether the unit begins with one of the UNIT_PREFIXES.
$stem = 'unit';
$prefix = substr($options->unit, 0, (int) strpos($options->unit, '-'));
if (in_array($prefix, self::UNIT_PREFIXES)) {
$stem = 'measure-unit';
}
$skeleton[] = $stem . '/' . $options->unit;
$skeleton[] = self::SYMBOLS_UNIT_WIDTH_DISPLAY_TYPE[$options->unitDisplay] ?? '';
return $skeleton;
}
/**
* @param string[] $skeleton
*
* @return string[]
*/
private function buildStylePercentSkeleton(array $skeleton, NumberFormatOptions $options): array
{
$skeleton[] = 'percent';
// By default, scale percentages by 100.
if ($options->scale === null) {
$skeleton[] = 'scale/100';
}
return $skeleton;
}
/**
* @param string[] $skeleton
*
* @return string[]
*/
private function buildNotation(array $skeleton, NumberFormatOptions $options): array
{
switch ($options->notation) {
case NumberFormatOptions::NOTATION_SCIENTIFIC:
case NumberFormatOptions::NOTATION_ENGINEERING:
// @phpstan-ignore-next-line
return $this->buildNotationSciEngSkeleton($options->notation, $skeleton, $options);
case NumberFormatOptions::NOTATION_COMPACT:
$skeleton = $this->buildNotationCompactSkeleton($skeleton, $options);
break;
}
$skeleton[] = $this->getSignDisplay($options);
return $skeleton;
}
/**
* @param string[] $skeleton
*
* @return string[]
*/
private function buildNotationSciEngSkeleton(string $type, array $skeleton, NumberFormatOptions $options): array
{
$notation = [$type, $this->getSignDisplay($options)];
$skeleton[] = implode('/', array_filter($notation));
return $skeleton;
}
/**
* @param string[] $skeleton
*
* @return string[]
*/
private function buildNotationCompactSkeleton(array $skeleton, NumberFormatOptions $options): array
{
$skeleton[] = self::SYMBOLS_COMPACT_DISPLAY[$options->compactDisplay] ?? 'compact-short';
return $skeleton;
}
/**
* @param string[] $skeleton
*
* @return string[]
*/
private function buildUseGrouping(array $skeleton, NumberFormatOptions $options): array
{
$skeleton[] = self::SYMBOLS_USE_GROUPING[$options->useGrouping] ?? '';
return $skeleton;
}
/**
* @param string[] $skeleton
*
* @return string[]
*/
private function buildRoundingMode(array $skeleton, NumberFormatOptions $options): array
{
$skeleton[] = self::SYMBOLS_ROUNDING_MODE[$options->roundingMode] ?? '';
return $skeleton;
}
/**
* @param string[] $skeleton
*
* @return string[]
*/
private function buildNumberingSystem(array $skeleton, NumberFormatOptions $options): array
{
if ($options->numberingSystem !== null) {
$skeleton[] = 'numbering-system/' . $options->numberingSystem;
}
return $skeleton;
}
/**
* @param string[] $skeleton
*
* @return string[]
*
* @throws InvalidArgumentException
*/
private function buildDigits(array $skeleton, NumberFormatOptions $options): array
{
$skeleton[] = $this->getIntegerDigitsStem($options);
$fractionDigitsStem = $this->getFractionDigitsStem($options);
$significantDigitsStem = $this->getSignificantDigitsStem($options);
$separator = ' ';
$roundingPriority = '';
if ($fractionDigitsStem && $significantDigitsStem) {
$separator = '/';
$roundingPriority = self::SYMBOLS_ROUNDING_PRIORITY[$options->roundingPriority] ?? '';
}
$stem = trim($fractionDigitsStem . $separator . $significantDigitsStem . $roundingPriority);
// Determine whether to display trailing zeros on fractions, and if
// this is currency but there's no precision stem, use the currency
// precision stem to indicate removal of trailing zeros.
if ($options->trailingZeroDisplay === NumberFormatOptions::TRAILING_ZERO_DISPLAY_STRIP_IF_INTEGER) {
if ($stem !== '') {
$stem .= '/w';
} elseif ($options->style === NumberFormatOptions::STYLE_CURRENCY) {
$skeleton[] = 'precision-currency-standard/w';
}
}
$skeleton[] = $stem;
// Special case for style: percent, which needs "precision-integer" if
// it has no special handling for fraction or significant digits.
if ($options->style === NumberFormatOptions::STYLE_PERCENT && !$fractionDigitsStem && !$significantDigitsStem) {
$skeleton[] = 'precision-integer';
}
return $skeleton;
}
/**
* @param string[] $skeleton
*
* @return string[]
*/
private function buildScale(array $skeleton, NumberFormatOptions $options): array
{
if ($options->scale !== null) {
$skeleton[] = 'scale/' . $options->scale;
}
return $skeleton;
}
private function getIntegerDigitsStem(NumberFormatOptions $options): string
{
if ($options->minimumIntegerDigits !== null) {
return 'integer-width/*' . str_repeat('0', $options->minimumIntegerDigits);
}
return '';
}
/**
* @throws InvalidArgumentException
*/
private function getFractionDigitsStem(NumberFormatOptions $options): string
{
if (
$options->maximumFractionDigits !== null
&& (int) $options->minimumFractionDigits > $options->maximumFractionDigits
) {
throw new InvalidArgumentException(
'minimumFractionDigits is greater than maximumFractionDigits',
);
}
$options->minimumFractionDigits = $this->getMinimumFractionDigits($options);
$options->maximumFractionDigits = $this->getMaximumFractionDigits($options);
if ($options->maximumFractionDigits === 0) {
return 'precision-integer';
}
$stem = str_pad(
str_repeat('0', (int) $options->minimumFractionDigits),
(int) $options->maximumFractionDigits,
'#',
);
if ($options->minimumFractionDigits !== null && $options->maximumFractionDigits === null) {
$stem .= '*';
}
return $stem ? ".$stem" : '';
}
/**
* @throws InvalidArgumentException
*/
private function getSignificantDigitsStem(NumberFormatOptions $options): string
{
if (
$options->maximumSignificantDigits !== null
&& (int) $options->minimumSignificantDigits > $options->maximumSignificantDigits
) {
throw new InvalidArgumentException(
'minimumSignificantDigits is greater than maximumSignificantDigits',
);
}
$stem = str_repeat('@', (int) $options->minimumSignificantDigits);
if ($stem === '' && $options->maximumSignificantDigits !== null) {
$stem = '@';
}
$stem = str_pad($stem, (int) $options->maximumSignificantDigits, '#');
if ($options->minimumSignificantDigits !== null && $options->maximumSignificantDigits === null) {
$stem .= '*';
}
return $stem;
}
private function getSignDisplay(NumberFormatOptions $options): string
{
// The sign display for accounting is handled in buildStyleCurrencySkeleton.
if (
$options->style === NumberFormatOptions::STYLE_CURRENCY
|| $options->currencySign === NumberFormatOptions::CURRENCY_SIGN_ACCOUNTING
) {
return '';
}
return self::SYMBOLS_SIGN_DISPLAY[$options->signDisplay] ?? '';
}
/**
* @return FractionDigitsType | null
*/
private function getMinimumFractionDigits(NumberFormatOptions $options): ?int
{
$minimumFractionDigits = $options->minimumFractionDigits;
if ($options->style === NumberFormatOptions::STYLE_CURRENCY) {
return $minimumFractionDigits;
}
if (
in_array($options->notation, self::SCI_ENG_NOTATION)
|| (
$options->style === NumberFormatOptions::STYLE_UNIT
&& $options->notation !== NumberFormatOptions::NOTATION_COMPACT
)
) {
$minimumFractionDigits = $minimumFractionDigits ?? 0;
}
return $minimumFractionDigits;
}
/**
* @return FractionDigitsType | null
*/
private function getMaximumFractionDigits(NumberFormatOptions $options): ?int
{
$maximumFractionDigits = $options->maximumFractionDigits;
if ($maximumFractionDigits !== null || $options->style === NumberFormatOptions::STYLE_CURRENCY) {
return $maximumFractionDigits;
}
if (
in_array($options->notation, self::SCI_ENG_NOTATION)
|| (
$options->style === NumberFormatOptions::STYLE_UNIT
&& $options->notation !== NumberFormatOptions::NOTATION_COMPACT
)
) {
$maximumFractionDigits = $options->minimumFractionDigits > 3 ? $maximumFractionDigits : 3;
}
return $maximumFractionDigits;
}
}