Passed
Push — master ( e0f448...f1081c )
by Alexander
02:57 queued 16s
created

NumericHelper::isInteger()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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