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

ADriver::elapsedTime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AlecRabbit\Spinner\Core\A;
6
7
use AlecRabbit\Spinner\Contract\IDriver;
8
use AlecRabbit\Spinner\Contract\IFrame;
9
use AlecRabbit\Spinner\Contract\ITimer;
10
use AlecRabbit\Spinner\Core\Output\Contract\IOutput;
11
use AlecRabbit\Spinner\Core\Sequencer;
12
13
abstract class ADriver implements IDriver
14
{
15
    protected int $previousFrameWidth = 0;
16
17
    public function __construct(
18
        protected readonly IOutput $output,
19
        protected readonly ITimer $timer,
20
        protected readonly bool $hideCursor,
21
        protected readonly string $interruptMessage,
22
        protected readonly string $finalMessage,
23
    ) {
24
    }
25
26
    public function erase(IFrame $frame): void
27
    {
28
        $this->output->write(
29
            Sequencer::eraseSequence($frame->width())
30
        );
31
    }
32
33
    public function display(IFrame $frame): void
34
    {
35
        $width = $frame->width();
36
        $widthDiff = $this->calculateWidthDiff($width);
37
38
        $this->output->write(
39
            [
40
                $frame->sequence(),
41
                $widthDiff > 0 ? Sequencer::eraseSequence($widthDiff) : '',
42
                Sequencer::moveBackSequence($width),
43
            ]
44
        );
45
    }
46
47
    protected function calculateWidthDiff(int $currentWidth): int
48
    {
49
        $diff = max($this->previousFrameWidth - $currentWidth, 0);
50
51
        $this->previousFrameWidth = $currentWidth;
52
53
        return $diff;
54
    }
55
56
    public function interrupt(?string $interruptMessage = null): void
57
    {
58
        $this->finalize($interruptMessage ?? $this->interruptMessage);
59
    }
60
61
    public function finalize(?string $finalMessage = null): void
62
    {
63
        $this->showCursor();
64
        $this->output->write($finalMessage ?? $this->finalMessage);
65
    }
66
67
    public function showCursor(): void
68
    {
69
        if ($this->hideCursor) {
70
            $this->output->write(
71
                Sequencer::showCursorSequence()
72
            );
73
        }
74
    }
75
76
    public function elapsedTime(): float
77
    {
78
        return $this->timer->elapsed();
79
    }
80
81
    public function initialize(): void
82
    {
83
        $this->hideCursor();
84
    }
85
86
    public function hideCursor(): void
87
    {
88
        if ($this->hideCursor) {
89
            $this->output->write(
90
                Sequencer::hideCursorSequence()
91
            );
92
        }
93
    }
94
}
95