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

AFloatValue   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 24
c 2
b 0
f 0
dl 0
loc 66
rs 10
wmc 9

7 Methods

Rating   Name   Duplication   Size   Complexity  
A checkBounds() 0 7 3
A getMin() 0 3 1
A getMax() 0 3 1
A __construct() 0 7 1
A getValue() 0 3 1
A setValue() 0 4 1
A assert() 0 16 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AlecRabbit\Spinner\Core\A;
6
7
use AlecRabbit\Spinner\Contract\IFloatValue;
8
use AlecRabbit\Spinner\Exception\InvalidArgumentException;
9
10
abstract class AFloatValue implements IFloatValue
11
{
12
    protected float $value;
13
14
    /**
15
     * @throws InvalidArgumentException
16
     */
17
    public function __construct(
18
        float $startValue = 0.0,
19
        protected readonly float $min = 0.0,
20
        protected readonly float $max = 1.0,
21
    ) {
22
        $this->setValue($startValue);
23
        self::assert($this);
24
    }
25
26
    /**
27
     * @throws InvalidArgumentException
28
     */
29
    private static function assert(AFloatValue $value): void
30
    {
31
        match (true) {
32
            $value->min > $value->max =>
33
            throw new InvalidArgumentException(
34
                sprintf(
35
                    'Max value should be greater than min value. Min: "%s", Max: "%s".',
36
                    $value->min,
37
                    $value->max,
38
                )
39
            ),
40
            $value->min === $value->max =>
41
            throw new InvalidArgumentException(
42
                'Min and Max values cannot be equal.'
43
            ),
44
            default => null,
45
        };
46
    }
47
48
    public function getMin(): float
49
    {
50
        return $this->min;
51
    }
52
53
    public function getMax(): float
54
    {
55
        return $this->max;
56
    }
57
58
    public function getValue(): float
59
    {
60
        return $this->value;
61
    }
62
63
    public function setValue(float $value): void
64
    {
65
        $this->value = $value;
66
        $this->checkBounds();
67
    }
68
69
    protected function checkBounds(): void
70
    {
71
        if ($this->value > $this->max) {
72
            $this->value = $this->max;
73
        }
74
        if ($this->value < $this->min) {
75
            $this->value = $this->min;
76
        }
77
    }
78
}
79