Test Failed
Pull Request — main (#372)
by
unknown
16:58 queued 06:32
created

MathUtils::stringToNumber()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 3
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MartinGeorgiev\Utils;
6
7
class MathUtils
8
{
9
    /**
10
     * Decides whether the provided $value is in a range delimited by $start and $end values.
11
     *
12
     * - If $start is null, then the comparison is "lesser than $end" only
13
     * - If $end is null, the comparison is "greater than $start" only
14
     * - The $(start|end)Inclusive determine whether the comparison is "lesser/greater than", or "lesser/greater or equal than"
15
     */
16
    public static function inRange(
17
        null|float|int $value,
18
        null|float|int $start = null,
19
        null|float|int $end = null,
20
        bool $startInclusive = true,
21
        bool $endInclusive = false,
22
    ): bool {
23
        if (null === $value) {
24
            return false;
25
        }
26
27
        if (null !== $start && null !== $end && (float) $start === (float) $end) {
28
            return (float) $value === (float) $start;
29
        }
30
31
        if (null === $start) {
32
            $startInclusive = true;
33
        }
34
35
        if (null === $end) {
36
            $endInclusive = true;
37
        }
38
39
        // Depending on this->range[Start/End]Inclusive, we will use (>= or >) and (<= or <) to work out where the value is
40
        $isGreater = $startInclusive ? $value >= $start : $value > $start;
41
        $isLesser = $endInclusive ? $value <= $end : $value < $end;
42
43
        return
44
            (null === $start || $isGreater)
45
            && (null === $end || $isLesser);
46
    }
47
48
    public static function stringToNumber(?string $number): null|float|int
49
    {
50
        if (!\is_numeric($number)) {
51
            return null;
52
        }
53
54
        return ((float) $number == (int) $number) ? (int) $number : (float) $number;
55
    }
56
}
57