|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace AlecRabbit\Spinner\Core\Output; |
|
6
|
|
|
|
|
7
|
|
|
use AlecRabbit\Spinner\Contract\Output\IBufferedOutput; |
|
8
|
|
|
use AlecRabbit\Spinner\Core\Contract\ISequenceState; |
|
9
|
|
|
use AlecRabbit\Spinner\Core\Feature\Resolver\Contract\IInitializationResolver; |
|
10
|
|
|
use AlecRabbit\Spinner\Core\Output\Contract\IConsoleCursor; |
|
11
|
|
|
use AlecRabbit\Spinner\Core\Output\Contract\ISequenceStateWriter; |
|
12
|
|
|
|
|
13
|
|
|
final class SequenceStateWriter implements ISequenceStateWriter |
|
14
|
|
|
{ |
|
15
|
|
|
private bool $initialized = false; |
|
16
|
|
|
|
|
17
|
|
|
public function __construct( |
|
18
|
|
|
private readonly IBufferedOutput $output, |
|
19
|
|
|
private readonly IConsoleCursor $cursor, |
|
20
|
|
|
private readonly IInitializationResolver $initializationResolver, |
|
21
|
|
|
) { |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
public function finalize(?string $finalMessage = null): void |
|
25
|
|
|
{ |
|
26
|
|
|
if ($this->initialized) { |
|
27
|
|
|
$finalMessage && $this->output->append($finalMessage); |
|
28
|
|
|
|
|
29
|
|
|
$this->cursor->show(); |
|
30
|
|
|
|
|
31
|
|
|
$this->output->flush(); |
|
32
|
|
|
|
|
33
|
|
|
$this->initialized = false; |
|
34
|
|
|
} |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function write(ISequenceState $state): void |
|
38
|
|
|
{ |
|
39
|
|
|
if ($this->initialized) { |
|
40
|
|
|
$this->output->append($state->getSequence()); |
|
41
|
|
|
|
|
42
|
|
|
$width = $state->getWidth(); |
|
43
|
|
|
$eraseWidth = |
|
44
|
|
|
max($state->getPreviousWidth() - $width, 0); |
|
45
|
|
|
|
|
46
|
|
|
$this->cursor |
|
47
|
|
|
->erase($eraseWidth) |
|
48
|
|
|
->moveLeft($width) |
|
49
|
|
|
; |
|
50
|
|
|
|
|
51
|
|
|
$this->output->flush(); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
public function erase(ISequenceState $state): void |
|
56
|
|
|
{ |
|
57
|
|
|
if ($this->initialized) { |
|
58
|
|
|
$this->cursor->erase( |
|
59
|
|
|
$state->getPreviousWidth() |
|
60
|
|
|
); |
|
61
|
|
|
|
|
62
|
|
|
$this->output->flush(); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
public function initialize(): void |
|
67
|
|
|
{ |
|
68
|
|
|
if ($this->initializationResolver->isEnabled()) { |
|
69
|
|
|
$this->initialized = true; |
|
70
|
|
|
|
|
71
|
|
|
$this->cursor->hide(); |
|
72
|
|
|
|
|
73
|
|
|
$this->output->flush(); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|