-
Notifications
You must be signed in to change notification settings - Fork 7
/
Number.php
488 lines (436 loc) · 17.4 KB
/
Number.php
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
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.10.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\I18n;
use NumberFormatter;
/**
* Number helper library.
*
* Methods to make numbers more readable.
*
* @link https://book.cakephp.org/4/en/core-libraries/number.html
*/
class Number
{
/**
* Default locale
*
* @var string
*/
public const DEFAULT_LOCALE = 'en_US';
/**
* Format type to format as currency
*
* @var string
*/
public const FORMAT_CURRENCY = 'currency';
/**
* Format type to format as currency, accounting style (negative numbers in parentheses)
*
* @var string
*/
public const FORMAT_CURRENCY_ACCOUNTING = 'currency_accounting';
/**
* ICU Constant for accounting format; not yet widely supported by INTL library.
* This will be able to go away once CakePHP minimum PHP requirement is 7.4.1 or higher.
* See UNUM_CURRENCY_ACCOUNTING in https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/unum_8h.html
*
* @var int
*/
public const CURRENCY_ACCOUNTING = 12;
/**
* A list of number formatters indexed by locale and type
*
* @var array
*/
protected static $_formatters = [];
/**
* Default currency used by Number::currency()
*
* @var string|null
*/
protected static $_defaultCurrency;
/**
* Default currency format used by Number::currency()
*
* @var string|null
*/
protected static $_defaultCurrencyFormat;
/**
* Formats a number with a level of precision.
*
* Options:
*
* - `locale`: The locale name to use for formatting the number, e.g. fr_FR
*
* @param float|string $value A floating point number.
* @param int $precision The precision of the returned number.
* @param array $options Additional options
* @return string Formatted float.
* @link https://book.cakephp.org/4/en/core-libraries/number.html#formatting-floating-point-numbers
*/
public static function precision($value, int $precision = 3, array $options = []): string
{
$formatter = static::formatter(['precision' => $precision, 'places' => $precision] + $options);
return $formatter->format($value);
}
/**
* Returns a formatted-for-humans file size.
*
* @param int|string $size Size in bytes
* @return string Human readable size
* @link https://book.cakephp.org/4/en/core-libraries/number.html#interacting-with-human-readable-values
*/
public static function toReadableSize($size): string
{
$size = (int)$size;
switch (true) {
case $size < 1024:
return __dn('cake', '{0,number,integer} Byte', '{0,number,integer} Bytes', $size, $size);
case round($size / 1024) < 1024:
return __d('cake', '{0,number,#,###.##} KB', $size / 1024);
case round($size / 1024 / 1024, 2) < 1024:
return __d('cake', '{0,number,#,###.##} MB', $size / 1024 / 1024);
case round($size / 1024 / 1024 / 1024, 2) < 1024:
return __d('cake', '{0,number,#,###.##} GB', $size / 1024 / 1024 / 1024);
default:
return __d('cake', '{0,number,#,###.##} TB', $size / 1024 / 1024 / 1024 / 1024);
}
}
/**
* Formats a number into a percentage string.
*
* Options:
*
* - `multiply`: Multiply the input value by 100 for decimal percentages.
* - `locale`: The locale name to use for formatting the number, e.g. fr_FR
*
* @param float|string $value A floating point number
* @param int $precision The precision of the returned number
* @param array $options Options
* @return string Percentage string
* @link https://book.cakephp.org/4/en/core-libraries/number.html#formatting-percentages
*/
public static function toPercentage($value, int $precision = 2, array $options = []): string
{
$options += ['multiply' => false, 'type' => NumberFormatter::PERCENT];
if (!$options['multiply']) {
$value = (float)$value / 100;
}
return static::precision($value, $precision, $options);
}
/**
* Formats a number into the correct locale format
*
* Options:
*
* - `places` - Minimum number or decimals to use, e.g 0
* - `precision` - Maximum Number of decimal places to use, e.g. 2
* - `pattern` - An ICU number pattern to use for formatting the number. e.g #,##0.00
* - `locale` - The locale name to use for formatting the number, e.g. fr_FR
* - `before` - The string to place before whole numbers, e.g. '['
* - `after` - The string to place after decimal numbers, e.g. ']'
*
* @param float|string $value A floating point number.
* @param array $options An array with options.
* @return string Formatted number
*/
public static function format($value, array $options = []): string
{
$formatter = static::formatter($options);
$options += ['before' => '', 'after' => ''];
return $options['before'] . $formatter->format((float)$value) . $options['after'];
}
/**
* Parse a localized numeric string and transform it in a float point
*
* Options:
*
* - `locale` - The locale name to use for parsing the number, e.g. fr_FR
* - `type` - The formatter type to construct, set it to `currency` if you need to parse
* numbers representing money.
*
* @param string $value A numeric string.
* @param array $options An array with options.
* @return float point number
*/
public static function parseFloat(string $value, array $options = []): float
{
$formatter = static::formatter($options);
return (float)$formatter->parse($value, NumberFormatter::TYPE_DOUBLE);
}
/**
* Formats a number into the correct locale format to show deltas (signed differences in value).
*
* ### Options
*
* - `places` - Minimum number or decimals to use, e.g 0
* - `precision` - Maximum Number of decimal places to use, e.g. 2
* - `locale` - The locale name to use for formatting the number, e.g. fr_FR
* - `before` - The string to place before whole numbers, e.g. '['
* - `after` - The string to place after decimal numbers, e.g. ']'
*
* @param float|string $value A floating point number
* @param array $options Options list.
* @return string formatted delta
*/
public static function formatDelta($value, array $options = []): string
{
$options += ['places' => 0];
$value = number_format((float)$value, $options['places'], '.', '');
$sign = $value > 0 ? '+' : '';
$options['before'] = isset($options['before']) ? $options['before'] . $sign : $sign;
return static::format($value, $options);
}
/**
* Formats a number into a currency format.
*
* ### Options
*
* - `locale` - The locale name to use for formatting the number, e.g. fr_FR
* - `fractionSymbol` - The currency symbol to use for fractional numbers.
* - `fractionPosition` - The position the fraction symbol should be placed
* valid options are 'before' & 'after'.
* - `before` - Text to display before the rendered number
* - `after` - Text to display after the rendered number
* - `zero` - The text to use for zero values, can be a string or a number. e.g. 0, 'Free!'
* - `places` - Number of decimal places to use. e.g. 2
* - `precision` - Maximum Number of decimal places to use, e.g. 2
* - `pattern` - An ICU number pattern to use for formatting the number. e.g #,##0.00
* - `useIntlCode` - Whether or not to replace the currency symbol with the international
* currency code.
*
* @param float|string $value Value to format.
* @param string|null $currency International currency name such as 'USD', 'EUR', 'JPY', 'CAD'
* @param array $options Options list.
* @return string Number formatted as a currency.
*/
public static function currency($value, ?string $currency = null, array $options = []): string
{
$value = (float)$value;
$currency = $currency ?: static::getDefaultCurrency();
if (isset($options['zero']) && !$value) {
return $options['zero'];
}
$formatter = static::formatter(['type' => static::getDefaultCurrencyFormat()] + $options);
$abs = abs($value);
if (!empty($options['fractionSymbol']) && $abs > 0 && $abs < 1) {
$value *= 100;
$pos = $options['fractionPosition'] ?? 'after';
return static::format($value, ['precision' => 0, $pos => $options['fractionSymbol']]);
}
$before = $options['before'] ?? '';
$after = $options['after'] ?? '';
$value = $formatter->formatCurrency($value, $currency);
return $before . $value . $after;
}
/**
* Getter/setter for default currency. This behavior is *deprecated* and will be
* removed in future versions of CakePHP.
*
* @deprecated 3.9.0 Use {@link getDefaultCurrency()} and {@link setDefaultCurrency()} instead.
* @param string|false|null $currency Default currency string to be used by {@link currency()}
* if $currency argument is not provided. If boolean false is passed, it will clear the
* currently stored value
* @return string|null Currency
*/
public static function defaultCurrency($currency = null): ?string
{
deprecationWarning(
'Number::defaultCurrency() is deprecated. ' .
'Use Number::setDefaultCurrency()/getDefaultCurrency() instead.'
);
if ($currency === false) {
static::setDefaultCurrency(null);
// This doesn't seem like a useful result to return, but it's what the old version did.
// Retaining it for backward compatibility.
return null;
}
if ($currency !== null) {
static::setDefaultCurrency($currency);
}
return static::getDefaultCurrency();
}
/**
* Getter for default currency
*
* @return string Currency
*/
public static function getDefaultCurrency(): string
{
if (static::$_defaultCurrency === null) {
$locale = ini_get('intl.default_locale') ?: static::DEFAULT_LOCALE;
$formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);
static::$_defaultCurrency = $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);
}
return static::$_defaultCurrency;
}
/**
* Setter for default currency
*
* @param string|null $currency Default currency string to be used by {@link currency()}
* if $currency argument is not provided. If null is passed, it will clear the
* currently stored value
* @return void
*/
public static function setDefaultCurrency(?string $currency = null): void
{
static::$_defaultCurrency = $currency;
}
/**
* Getter for default currency format
*
* @return string Currency Format
*/
public static function getDefaultCurrencyFormat(): string
{
if (static::$_defaultCurrencyFormat === null) {
static::$_defaultCurrencyFormat = static::FORMAT_CURRENCY;
}
return static::$_defaultCurrencyFormat;
}
/**
* Setter for default currency format
*
* @param string|null $currencyFormat Default currency format to be used by currency()
* if $currencyFormat argument is not provided. If null is passed, it will clear the
* currently stored value
* @return void
*/
public static function setDefaultCurrencyFormat($currencyFormat = null): void
{
static::$_defaultCurrencyFormat = $currencyFormat;
}
/**
* Returns a formatter object that can be reused for similar formatting task
* under the same locale and options. This is often a speedier alternative to
* using other methods in this class as only one formatter object needs to be
* constructed.
*
* ### Options
*
* - `locale` - The locale name to use for formatting the number, e.g. fr_FR
* - `type` - The formatter type to construct, set it to `currency` if you need to format
* numbers representing money or a NumberFormatter constant.
* - `places` - Number of decimal places to use. e.g. 2
* - `precision` - Maximum Number of decimal places to use, e.g. 2
* - `pattern` - An ICU number pattern to use for formatting the number. e.g #,##0.00
* - `useIntlCode` - Whether or not to replace the currency symbol with the international
* currency code.
*
* @param array $options An array with options.
* @return \NumberFormatter The configured formatter instance
*/
public static function formatter(array $options = []): NumberFormatter
{
$locale = $options['locale'] ?? ini_get('intl.default_locale');
if (!$locale) {
$locale = static::DEFAULT_LOCALE;
}
$type = NumberFormatter::DECIMAL;
if (!empty($options['type'])) {
$type = $options['type'];
if ($options['type'] === static::FORMAT_CURRENCY) {
$type = NumberFormatter::CURRENCY;
} elseif ($options['type'] === static::FORMAT_CURRENCY_ACCOUNTING) {
if (defined('NumberFormatter::CURRENCY_ACCOUNTING')) {
$type = NumberFormatter::CURRENCY_ACCOUNTING;
} else {
$type = static::CURRENCY_ACCOUNTING;
}
}
}
if (!isset(static::$_formatters[$locale][$type])) {
static::$_formatters[$locale][$type] = new NumberFormatter($locale, $type);
}
/** @var \NumberFormatter $formatter */
$formatter = static::$_formatters[$locale][$type];
// PHP 8.0.0 - 8.0.6 throws an exception when cloning NumberFormatter after a failed parse
if (version_compare(PHP_VERSION, '8.0.6', '>') || version_compare(PHP_VERSION, '8.0.0', '<')) {
$options = array_intersect_key($options, [
'places' => null,
'precision' => null,
'pattern' => null,
'useIntlCode' => null,
]);
if (empty($options)) {
return $formatter;
}
}
$formatter = clone $formatter;
return static::_setAttributes($formatter, $options);
}
/**
* Configure formatters.
*
* @param string $locale The locale name to use for formatting the number, e.g. fr_FR
* @param int $type The formatter type to construct. Defaults to NumberFormatter::DECIMAL.
* @param array $options See Number::formatter() for possible options.
* @return void
*/
public static function config(string $locale, int $type = NumberFormatter::DECIMAL, array $options = []): void
{
static::$_formatters[$locale][$type] = static::_setAttributes(
new NumberFormatter($locale, $type),
$options
);
}
/**
* Set formatter attributes
*
* @param \NumberFormatter $formatter Number formatter instance.
* @param array $options See Number::formatter() for possible options.
* @return \NumberFormatter
*/
protected static function _setAttributes(NumberFormatter $formatter, array $options = []): NumberFormatter
{
if (isset($options['places'])) {
$formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $options['places']);
}
if (isset($options['precision'])) {
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $options['precision']);
}
if (!empty($options['pattern'])) {
$formatter->setPattern($options['pattern']);
}
if (!empty($options['useIntlCode'])) {
// One of the odd things about ICU is that the currency marker in patterns
// is denoted with ¤, whereas the international code is marked with ¤¤,
// in order to use the code we need to simply duplicate the character wherever
// it appears in the pattern.
$pattern = trim(str_replace('¤', '¤¤ ', $formatter->getPattern()));
$formatter->setPattern($pattern);
}
return $formatter;
}
/**
* Returns a formatted integer as an ordinal number string (e.g. 1st, 2nd, 3rd, 4th, [...])
*
* ### Options
*
* - `type` - The formatter type to construct, set it to `currency` if you need to format
* numbers representing money or a NumberFormatter constant.
*
* For all other options see formatter().
*
* @param int|float $value An integer
* @param array $options An array with options.
* @return string
*/
public static function ordinal($value, array $options = []): string
{
return static::formatter(['type' => NumberFormatter::ORDINAL] + $options)->format($value);
}
}