|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Strings; |
|
6
|
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
|
8
|
|
|
|
|
9
|
|
|
use function gettype; |
|
10
|
|
|
use function in_array; |
|
11
|
|
|
use function is_bool; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Provides static methods to work with numeric strings. |
|
15
|
|
|
*/ |
|
16
|
|
|
final class NumericHelper |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* Converts number to its ordinal English form. For example, converts 13 to 13th, 2 to 2nd etc. |
|
20
|
|
|
* |
|
21
|
|
|
* @param float|int|string $value The number to get its ordinal value. |
|
22
|
|
|
*/ |
|
23
|
2 |
|
public static function toOrdinal(mixed $value): string |
|
24
|
|
|
{ |
|
25
|
2 |
|
if (!is_numeric($value)) { |
|
26
|
1 |
|
$type = gettype($value); |
|
27
|
1 |
|
throw new InvalidArgumentException("Value must be numeric. $type given."); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
1 |
|
if (fmod((float)$value, 1) !== 0.00) { |
|
31
|
1 |
|
return (string)$value; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
1 |
|
if (in_array($value % 100, [11, 12, 13], true)) { |
|
35
|
1 |
|
return $value . 'th'; |
|
36
|
|
|
} |
|
37
|
1 |
|
return match ($value % 10) { |
|
38
|
1 |
|
1 => $value . 'st', |
|
39
|
1 |
|
2 => $value . 'nd', |
|
40
|
1 |
|
3 => $value . 'rd', |
|
41
|
1 |
|
default => $value . 'th', |
|
42
|
1 |
|
}; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Returns string representation of a number value without thousands separators and with dot as decimal separator. |
|
47
|
|
|
* |
|
48
|
|
|
* @param bool|float|int|string $value |
|
49
|
|
|
* |
|
50
|
|
|
* @throws InvalidArgumentException if value is not scalar. |
|
51
|
|
|
*/ |
|
52
|
10 |
|
public static function normalize(mixed $value): string |
|
53
|
|
|
{ |
|
54
|
|
|
/** @psalm-suppress DocblockTypeContradiction */ |
|
55
|
10 |
|
if (!is_scalar($value)) { |
|
56
|
1 |
|
$type = gettype($value); |
|
57
|
1 |
|
throw new InvalidArgumentException("Value must be scalar. $type given."); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
9 |
|
if (is_bool($value)) { |
|
61
|
2 |
|
$value = $value ? '1' : '0'; |
|
62
|
|
|
} else { |
|
63
|
7 |
|
$value = (string)$value; |
|
64
|
|
|
} |
|
65
|
9 |
|
$value = str_replace([' ', ','], ['', '.'], $value); |
|
66
|
9 |
|
return preg_replace('/\.(?=.*\.)/', '', $value); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* Checks whether the given string is an integer number. |
|
71
|
|
|
*/ |
|
72
|
9 |
|
public static function isInteger(mixed $value): bool |
|
73
|
|
|
{ |
|
74
|
9 |
|
return filter_var($value, FILTER_VALIDATE_INT) !== false; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|