Passed
Push — master ( 823aee...b9b37f )
by Alec
13:15 queued 12s
created

IntNormalizer::normalize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
declare(strict_types=1);
4
// 14.03.23
5
6
namespace AlecRabbit\Spinner\Core;
7
8
use AlecRabbit\Spinner\Contract\IIntNormalizer;
9
use AlecRabbit\Spinner\Exception\InvalidArgumentException;
10
11
final class IntNormalizer implements IIntNormalizer
12
{
13
    private static int $divisor = self::DEFAULT_DIVISOR;
14
    private static int $min = self::DEFAULT_MIN;
15
16
    public static function normalize(int $interval): int
17
    {
18
        $result = (int)round($interval / self::$divisor) * self::$divisor;
19
20
        if (self::$min > $result) {
21
            return self::$min;
22
        }
23
24
        return $result;
25
    }
26
27
    public static function getDivisor(): int
28
    {
29
        return self::$divisor;
30
    }
31
32
33
    /** @inheritdoc */
34
    public static function overrideDivisor(int $divisor): void
35
    {
36
        self::assertDivisor($divisor);
37
        self::$divisor = $divisor;
38
    }
39
40
    /**
41
     * @throws InvalidArgumentException
42
     */
43
    private static function assertDivisor(int $divisor): void
44
    {
45
        match (true) {
46
            0 >= $divisor => throw new InvalidArgumentException('Divisor should be greater than 0.'),
47
            $divisor > self::MAX_DIVISOR => throw new InvalidArgumentException(
48
                sprintf('Divisor should be less than %s.', self::MAX_DIVISOR)
49
            ),
50
            default => null,
51
        };
52
    }
53
54
    /** @inheritdoc */
55
56
    public static function overrideMin(int $min): void
57
    {
58
        self::assertMin($min);
59
        self::$min = $min;
60
    }
61
62
    /**
63
     * @throws InvalidArgumentException
64
     */
65
    private static function assertMin(int $min): void
66
    {
67
        if (0 > $min) {
68
            throw new InvalidArgumentException('Min should be greater than 0.');
69
        }
70
    }
71
}
72