Passed
Pull Request — master (#39)
by Alexander
06:59
created

NumericHelper::toOrdinal()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 15
nc 7
nop 1
dl 0
loc 22
ccs 15
cts 15
cp 1
crap 7
rs 8.8333
c 1
b 0
f 0
1
<?php
2
3
namespace Yiisoft\Strings;
4
5
/**
6
 * Provides static methods to work with numeric strings.
7
 */
8
final class NumericHelper
9
{
10
    /**
11
     * Converts number to its ordinal English form. For example, converts 13 to 13th, 2 to 2nd etc.
12
     * @param int|float|string $value The number to get its ordinal value.
13
     * @return string
14
     */
15 2
    public static function toOrdinal($value): string
16
    {
17 2
        if (!is_numeric($value)) {
18 1
            throw new \InvalidArgumentException('Value must be numeric.');
19
        }
20
21 1
        if (fmod($value, 1) !== 0.00) {
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type string; however, parameter $x of fmod() does only seem to accept double, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

21
        if (fmod(/** @scrutinizer ignore-type */ $value, 1) !== 0.00) {
Loading history...
22 1
            return $value;
23
        }
24
25 1
        if (\in_array($value % 100, [11, 12, 13], true)) {
26 1
            return $value . 'th';
27
        }
28 1
        switch ($value % 10) {
29 1
            case 1:
30 1
                return $value . 'st';
31 1
            case 2:
32 1
                return $value . 'nd';
33 1
            case 3:
34 1
                return $value . 'rd';
35
            default:
36 1
                return $value . 'th';
37
        }
38
    }
39
40
    /**
41
     * Returns string representation of a number value without thousands separators and with dot as decimal separator.
42
     * @param int|float|string $value
43
     * @return string
44
     */
45 6
    public static function normalize($value): string
46
    {
47 6
        if (!is_scalar($value)) {
0 ignored issues
show
introduced by
The condition is_scalar($value) is always true.
Loading history...
48 1
            throw new \InvalidArgumentException('Value must be scalar.');
49
        }
50 5
        $value = str_replace([" ", ","], ["", "."], $value);
51 5
        return preg_replace('/\.(?=.*\.)/', '', $value);
52
    }
53
}
54