Skip to content

Commit c207842

Browse files
authored
Merge pull request #32 from seregazhuk/improve-spinner-output
Extract cursor manipulations in a separate class
2 parents 224d33c + 7403e9d commit c207842

File tree

3 files changed

+40
-11
lines changed

3 files changed

+40
-11
lines changed

src/Screen/Cursor.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace seregazhuk\PhpWatcher\Screen;
4+
5+
final class Cursor
6+
{
7+
public function startOfLine(): void
8+
{
9+
echo "\033[1D";
10+
}
11+
12+
public function erase(): void
13+
{
14+
echo "\033[1K";
15+
}
16+
17+
public function write(int $foregroundColor, string $text): void
18+
{
19+
echo "\e[38;5;{$foregroundColor}m{$text}\e[0m";
20+
}
21+
22+
public function hide(): void
23+
{
24+
echo "\033[?25l";
25+
}
26+
}

src/Screen/Screen.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,6 @@ public function start(string $command): void
6767

6868
public function restarting(string $command): void
6969
{
70-
$this->output->writeln('');
7170
$this->spinner->erase();
7271
$this->output->writeln('');
7372
$this->info('restarting due to changes...');

src/Screen/Spinner.php

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -68,14 +68,21 @@ final class Spinner
6868
197
6969
];
7070

71+
private $cursor;
72+
7173
private $currentFrameIndex = 0;
7274
private $currentColorIndex = 0;
7375

76+
public function __construct()
77+
{
78+
$this->cursor = new Cursor();
79+
}
80+
7481
public function spin(): void
7582
{
83+
$this->erase();
7684
$this->output();
7785
$this->increment();
78-
$this->hideCursor();
7986
}
8087

8188
public function interval(): float
@@ -85,12 +92,12 @@ public function interval(): float
8592

8693
public function erase(): void
8794
{
88-
echo "\033[1K";
95+
$this->cursor->erase();
8996
}
9097

91-
private function currentColor(): string
98+
private function currentColor(): int
9299
{
93-
return '38;5;' . self::COLORS[$this->currentColorIndex]. 'm';
100+
return self::COLORS[$this->currentColorIndex];
94101
}
95102

96103
private function currentFrame(): string
@@ -100,12 +107,9 @@ private function currentFrame(): string
100107

101108
private function output(): void
102109
{
103-
echo "\e[{$this->currentColor()}{$this->currentFrame()}\e[0m\r";
104-
}
105-
106-
private function hideCursor(): void
107-
{
108-
echo "\033[?25l";
110+
$this->cursor->write($this->currentColor(), $this->currentFrame());
111+
$this->cursor->hide();
112+
$this->cursor->startOfLine();
109113
}
110114

111115
private function increment(): void

0 commit comments

Comments
 (0)