Debian Codegraph @

lib/3rdParty/composer/illuminate/support/Number.php

raw symbols SCIP
1 <?php
2
3 namespace Illuminate\Support;
4
5 use Illuminate\Support\Traits\Macroable;
6 use NumberFormatter;
7 use RuntimeException;
8
9 class Number
10 {
11 use Macroable;
12
13 /**
14 * The current default locale.
15 *
16 * @var string
17 */
18 protected static $locale = 'en';
19
20 /**
21 * The current default currency.
22 *
23 * @var string
24 */
25 protected static $currency = 'USD';
26
27 /**
28 * Format the given number according to the current locale.
29 *
30 * @param int|float $number
31 * @param int|null $precision
32 * @param int|null $maxPrecision
33 * @param string|null $locale
34 * @return string|false
35 */
36 public static function format(int|float $number, ?int $precision = null, ?int $maxPrecision = null, ?string $locale = null)
37 {
38 static::ensureIntlExtensionIsInstalled();
39
40 $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::DECIMAL);
41
42 if (! is_null($maxPrecision)) {
43 $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $maxPrecision);
44 } elseif (! is_null($precision)) {
45 $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision);
46 }
47
48 return $formatter->format($number);
49 }
50
51 /**
52 * Parse the given string according to the specified format type.
53 *
54 * @param string $string
55 * @param int|null $type
56 * @param string|null $locale
57 * @return int|float|false
58 */
59 public static function parse(string $string, ?int $type = NumberFormatter::TYPE_DOUBLE, ?string $locale = null): int|float|false
60 {
61 static::ensureIntlExtensionIsInstalled();
62
63 $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::DECIMAL);
64
65 return $formatter->parse($string, $type);
66 }
67
68 /**
69 * Parse a string into an integer according to the specified locale.
70 *
71 * @param string $string
72 * @param string|null $locale
73 * @return int|false
74 */
75 public static function parseInt(string $string, ?string $locale = null): int|false
76 {
77 return self::parse($string, NumberFormatter::TYPE_INT32, $locale);
78 }
79
80 /**
81 * Parse a string into a float according to the specified locale.
82 *
83 * @param string $string
84 * @param string|null $locale
85 * @return float|false
86 */
87 public static function parseFloat(string $string, ?string $locale = null): float|false
88 {
89 return self::parse($string, NumberFormatter::TYPE_DOUBLE, $locale);
90 }
91
92 /**
93 * Spell out the given number in the given locale.
94 *
95 * @param int|float $number
96 * @param string|null $locale
97 * @param int|null $after
98 * @param int|null $until
99 * @return string
100 */
101 public static function spell(int|float $number, ?string $locale = null, ?int $after = null, ?int $until = null)
102 {
103 static::ensureIntlExtensionIsInstalled();
104
105 if (! is_null($after) && $number <= $after) {
106 return static::format($number, locale: $locale);
107 }
108
109 if (! is_null($until) && $number >= $until) {
110 return static::format($number, locale: $locale);
111 }
112
113 $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::SPELLOUT);
114
115 return $formatter->format($number);
116 }
117
118 /**
119 * Convert the given number to ordinal form.
120 *
121 * @param int|float $number
122 * @param string|null $locale
123 * @return string
124 */
125 public static function ordinal(int|float $number, ?string $locale = null)
126 {
127 static::ensureIntlExtensionIsInstalled();
128
129 $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::ORDINAL);
130
131 return $formatter->format($number);
132 }
133
134 /**
135 * Spell out the given number in the given locale in ordinal form.
136 *
137 * @param int|float $number
138 * @param string|null $locale
139 * @return string
140 */
141 public static function spellOrdinal(int|float $number, ?string $locale = null)
142 {
143 static::ensureIntlExtensionIsInstalled();
144
145 $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::SPELLOUT);
146
147 $formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET, '%spellout-ordinal');
148
149 return $formatter->format($number);
150 }
151
152 /**
153 * Convert the given number to its percentage equivalent.
154 *
155 * @param int|float $number
156 * @param int $precision
157 * @param int|null $maxPrecision
158 * @param string|null $locale
159 * @return string|false
160 */
161 public static function percentage(int|float $number, int $precision = 0, ?int $maxPrecision = null, ?string $locale = null)
162 {
163 static::ensureIntlExtensionIsInstalled();
164
165 $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::PERCENT);
166
167 if (! is_null($maxPrecision)) {
168 $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $maxPrecision);
169 } else {
170 $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision);
171 }
172
173 return $formatter->format($number / 100);
174 }
175
176 /**
177 * Convert the given number to its currency equivalent.
178 *
179 * @param int|float $number
180 * @param string $in
181 * @param string|null $locale
182 * @param int|null $precision
183 * @return string|false
184 */
185 public static function currency(int|float $number, string $in = '', ?string $locale = null, ?int $precision = null)
186 {
187 static::ensureIntlExtensionIsInstalled();
188
189 $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::CURRENCY);
190
191 if (! is_null($precision)) {
192 $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision);
193 }
194
195 return $formatter->formatCurrency($number, ! empty($in) ? $in : static::$currency);
196 }
197
198 /**
199 * Convert the given number to its file size equivalent.
200 *
201 * @param int|float $bytes
202 * @param int $precision
203 * @param int|null $maxPrecision
204 * @return string
205 */
206 public static function fileSize(int|float $bytes, int $precision = 0, ?int $maxPrecision = null)
207 {
208 $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
209
210 $unitCount = count($units);
211
212 for ($i = 0; (abs($bytes) / 1024) > 0.9 && ($i < $unitCount - 1); $i++) {
213 $bytes /= 1024;
214 }
215
216 return sprintf('%s %s', static::format($bytes, $precision, $maxPrecision), $units[$i]);
217 }
218
219 /**
220 * Convert the number to its human-readable equivalent.
221 *
222 * @param int|float $number
223 * @param int $precision
224 * @param int|null $maxPrecision
225 * @return string|false
226 */
227 public static function abbreviate(int|float $number, int $precision = 0, ?int $maxPrecision = null)
228 {
229 return static::forHumans($number, $precision, $maxPrecision, abbreviate: true);
230 }
231
232 /**
233 * Convert the number to its human-readable equivalent.
234 *
235 * @param int|float $number
236 * @param int $precision
237 * @param int|null $maxPrecision
238 * @param bool $abbreviate
239 * @return string|false
240 */
241 public static function forHumans(int|float $number, int $precision = 0, ?int $maxPrecision = null, bool $abbreviate = false)
242 {
243 return static::summarize($number, $precision, $maxPrecision, $abbreviate ? [
244 3 => 'K',
245 6 => 'M',
246 9 => 'B',
247 12 => 'T',
248 15 => 'Q',
249 ] : [
250 3 => ' thousand',
251 6 => ' million',
252 9 => ' billion',
253 12 => ' trillion',
254 15 => ' quadrillion',
255 ]);
256 }
257
258 /**
259 * Convert the number to its human-readable equivalent.
260 *
261 * @param int|float $number
262 * @param int $precision
263 * @param int|null $maxPrecision
264 * @param array $units
265 * @return string|false
266 */
267 protected static function summarize(int|float $number, int $precision = 0, ?int $maxPrecision = null, array $units = [])
268 {
269 if (empty($units)) {
270 $units = [
271 3 => 'K',
272 6 => 'M',
273 9 => 'B',
274 12 => 'T',
275 15 => 'Q',
276 ];
277 }
278
279 switch (true) {
280 case (float) $number === 0.0:
281 return $precision > 0 ? static::format(0, $precision, $maxPrecision) : '0';
282 case $number < 0:
283 return sprintf('-%s', static::summarize(abs($number), $precision, $maxPrecision, $units));
284 case $number >= 1e15:
285 return sprintf('%s'.end($units), static::summarize($number / 1e15, $precision, $maxPrecision, $units));
286 }
287
288 $numberExponent = floor(log10($number));
289 $displayExponent = $numberExponent - ($numberExponent % 3);
290 $number /= pow(10, $displayExponent);
291
292 return trim(sprintf('%s%s', static::format($number, $precision, $maxPrecision), $units[$displayExponent] ?? ''));
293 }
294
295 /**
296 * Clamp the given number between the given minimum and maximum.
297 *
298 * @param int|float $number
299 * @param int|float $min
300 * @param int|float $max
301 * @return int|float
302 */
303 public static function clamp(int|float $number, int|float $min, int|float $max)
304 {
305 return min(max($number, $min), $max);
306 }
307
308 /**
309 * Split the given number into pairs of min/max values.
310 *
311 * @param int|float $to
312 * @param int|float $by
313 * @param int|float $start
314 * @param int|float $offset
315 * @return list<array{int|float, int|float}>
316 */
317 public static function pairs(int|float $to, int|float $by, int|float $start = 0, int|float $offset = 1)
318 {
319 if ($by == 0) {
320 throw new \InvalidArgumentException('The $by argument must not be zero.');
321 }
322
323 $by = abs($by);
324
325 $output = [];
326
327 for ($lower = $start; $lower < $to; $lower += $by) {
328 $upper = $lower + $by - $offset;
329
330 if ($upper > $to) {
331 $upper = $to;
332 }
333
334 $output[] = [$lower, $upper];
335 }
336
337 return $output;
338 }
339
340 /**
341 * Remove any trailing zero digits after the decimal point of the given number.
342 *
343 * @param int|float $number
344 * @return int|float
345 */
346 public static function trim(int|float $number)
347 {
348 if (is_infinite($number) || is_nan($number)) {
349 return $number;
350 }
351
352 return json_decode(json_encode($number));
353 }
354
355 /**
356 * Execute the given callback using the given locale.
357 *
358 * @template TReturn
359 *
360 * @param string $locale
361 * @param callable(): TReturn $callback
362 * @return TReturn
363 */
364 public static function withLocale(string $locale, callable $callback)
365 {
366 $previousLocale = static::$locale;
367
368 static::useLocale($locale);
369
370 try {
371 return $callback();
372 } finally {
373 static::useLocale($previousLocale);
374 }
375 }
376
377 /**
378 * Execute the given callback using the given currency.
379 *
380 * @template TReturn
381 *
382 * @param string $currency
383 * @param callable(): TReturn $callback
384 * @return TReturn
385 */
386 public static function withCurrency(string $currency, callable $callback)
387 {
388 $previousCurrency = static::$currency;
389
390 static::useCurrency($currency);
391
392 try {
393 return $callback();
394 } finally {
395 static::useCurrency($previousCurrency);
396 }
397 }
398
399 /**
400 * Set the default locale.
401 *
402 * @param string $locale
403 * @return void
404 */
405 public static function useLocale(string $locale)
406 {
407 static::$locale = $locale;
408 }
409
410 /**
411 * Set the default currency.
412 *
413 * @param string $currency
414 * @return void
415 */
416 public static function useCurrency(string $currency)
417 {
418 static::$currency = $currency;
419 }
420
421 /**
422 * Get the default locale.
423 *
424 * @return string
425 */
426 public static function defaultLocale()
427 {
428 return static::$locale;
429 }
430
431 /**
432 * Get the default currency.
433 *
434 * @return string
435 */
436 public static function defaultCurrency()
437 {
438 return static::$currency;
439 }
440
441 /**
442 * Ensure the "intl" PHP extension is installed.
443 *
444 * @return void
445 *
446 * @throws \RuntimeException
447 */
448 protected static function ensureIntlExtensionIsInstalled()
449 {
450 if (! extension_loaded('intl')) {
451 $method = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function'];
452
453 throw new RuntimeException('The "intl" PHP extension is required to use the ['.$method.'] method.');
454 }
455 }
456 }