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

AProgressValue::autoFinish()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 2
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AlecRabbit\Spinner\Extras\A;
6
7
use AlecRabbit\Spinner\Core\A\AFloatValue;
8
use AlecRabbit\Spinner\Exception\InvalidArgumentException;
9
use AlecRabbit\Spinner\Extras\Contract\IProgressValue;
10
11
abstract class AProgressValue extends AFloatValue implements IProgressValue
12
{
13
    protected bool $finished = false;
14
    protected float $stepValue;
15
16
    /**
17
     * @throws InvalidArgumentException
18
     */
19
    public function __construct(
20
        float $startValue = 0.0,
21
        float $min = 0.0,
22
        float $max = 1.0,
23
        protected readonly int $steps = 100,
24
        protected readonly bool $autoFinish = true,
25
    ) {
26
        parent::__construct($startValue, $min, $max);
27
        self::assert($this);
28
        $this->stepValue = ($this->max - $this->min) / $this->steps;
29
    }
30
31
    /**
32
     * @throws InvalidArgumentException
33
     */
34
    private static function assert(AProgressValue $value): void
35
    {
36
        match (true) {
37
            0 > $value->steps || 0 === $value->steps =>
38
            throw new InvalidArgumentException(
39
                sprintf(
40
                    'Steps should be greater than 0. Steps: "%s".',
41
                    $value->steps,
42
                )
43
            ),
44
            default => null,
45
        };
46
    }
47
48
    /** @inheritdoc */
49
    public function advance(int $steps = 1): void
50
    {
51
        if ($this->finished) {
52
            return;
53
        }
54
55
        $this->value += $steps * $this->stepValue;
56
        $this->checkBounds();
57
        $this->autoFinish();
58
    }
59
60
    protected function autoFinish(): void
61
    {
62
        if ($this->autoFinish && $this->value >= $this->max) {
63
            $this->finish();
64
        }
65
    }
66
67
    public function finish(): void
68
    {
69
        $this->finished = true;
70
        $this->value = $this->max;
71
    }
72
73
    public function getSteps(): int
74
    {
75
        return $this->steps;
76
    }
77
78
    public function isFinished(): bool
79
    {
80
        return $this->finished;
81
    }
82
}
83