Test Failed
Pull Request — master (#63)
by Alexander
05:31 queued 02:43
created

NumericHelper   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 23
c 4
b 0
f 0
dl 0
loc 61
ccs 22
cts 22
cp 1
rs 10
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A normalize() 0 11 2
B toOrdinal() 0 23 7
A isInteger() 0 3 1
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
     */
68
    public static function isInteger($value): bool
69
    {
70
        return filter_var($value, FILTER_VALIDATE_INT); 
71
    }
72
}
73