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