Test Failed
Pull Request — master (#83)
by Alexander
04:00 queued 01:35
created

NumericHelper::toOrdinal()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 12
nc 4
nop 1
dl 0
loc 19
ccs 11
cts 11
cp 1
crap 4
rs 9.8666
c 2
b 0
f 0
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
    public static function toOrdinal(float|int|string $value): string
24
    {
25 2
        if (!is_numeric($value)) {
26
            $type = gettype($value);
27 2
            throw new InvalidArgumentException("Value must be numeric. $type given.");
28 1
        }
29 1
30
        if (fmod((float)$value, 1) !== 0.00) {
31
            return (string)$value;
32 1
        }
33 1
34
        if (in_array($value % 100, [11, 12, 13], true)) {
35
            return $value . 'th';
36 1
        }
37 1
        return match ($value % 10) {
38
            1 => $value . 'st',
39 1
            2 => $value . 'nd',
40 1
            3 => $value . 'rd',
41 1
            default => $value . 'th',
42 1
        };
43 1
    }
44 1
45 1
    /**
46
     * Returns string representation of a number value without thousands separators and with dot as decimal separator.
47 1
     *
48
     * @throws InvalidArgumentException if value is not scalar.
49
     */
50
    public static function normalize(bool|float|int|string $value): string
51
    {
52
        /** @psalm-suppress DocblockTypeContradiction */
53
        if (!is_scalar($value)) {
0 ignored issues
show
introduced by
The condition is_scalar($value) is always true.
Loading history...
54
            $type = gettype($value);
55
            throw new InvalidArgumentException("Value must be scalar. $type given.");
56
        }
57
58
        if (is_bool($value)) {
59
            $value = $value ? '1' : '0';
60 10
        } else {
61
            $value = (string)$value;
62
        }
63 10
        $value = str_replace([' ', ','], ['', '.'], $value);
64 1
        return preg_replace('/\.(?=.*\.)/', '', $value);
65 1
    }
66
67
    /**
68 9
     * Checks whether the given string is an integer number.
69 2
     */
70
    public static function isInteger(mixed $value): bool
71 7
    {
72
        return filter_var($value, FILTER_VALIDATE_INT) !== false;
73 9
    }
74
}
75