Passed
Push — master ( de3d61...be839c )
by Alec
13:42 queued 13s
created

DriverOutput::erase()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
6
namespace AlecRabbit\Spinner\Core\Output;
7
8
use AlecRabbit\Spinner\Contract\Output\IBufferedOutput;
9
use AlecRabbit\Spinner\Core\Contract\ISpinnerState;
10
use AlecRabbit\Spinner\Core\Output\Contract\IConsoleCursor;
11
use AlecRabbit\Spinner\Core\Output\Contract\IDriverOutput;
12
13
final class DriverOutput implements IDriverOutput
14
{
15
    private bool $initialized = false;
16
17
    public function __construct(
18
        protected readonly IBufferedOutput $output,
19
        protected readonly IConsoleCursor $cursor,
20
    ) {
21
    }
22
23
    public function finalize(?string $finalMessage = null): void
24
    {
25
        if ($this->initialized) {
26
            $this->cursor->show();
27
            $finalMessage && $this->output->write($finalMessage);
28
        }
29
    }
30
31
    public function write(ISpinnerState $spinnerState): void
32
    {
33
        if ($this->initialized) {
34
            $this->output->bufferedWrite($spinnerState->getSequence());
35
36
            $width = $spinnerState->getWidth();
37
            $eraseWidth = max($spinnerState->getPreviousWidth() - $width, 0);
38
39
            $this->cursor->erase($eraseWidth)->moveLeft($width);
40
41
            $this->output->flush();
42
        }
43
    }
44
45
    public function erase(ISpinnerState $spinnerState): void
46
    {
47
        if ($this->initialized) {
48
            $this->cursor->erase($spinnerState->getPreviousWidth())->flush();
49
        }
50
    }
51
52
    public function initialize(): void
53
    {
54
        $this->initialized = true;
55
        $this->cursor->hide();
56
    }
57
}
58