diff --git a/src/Output/ConsoleOutput.php b/src/Output/ConsoleOutput.php index 60381d62..0705a292 100644 --- a/src/Output/ConsoleOutput.php +++ b/src/Output/ConsoleOutput.php @@ -11,6 +11,11 @@ class ConsoleOutput extends SymfonyConsoleOutput */ protected int $newLinesWritten = 1; + /** + * Ignore incoming new lines, keeping the previous $newLinesWritten value. + */ + protected bool $ignoreNewLines = false; + /** * How many new lines were written by the last output. */ @@ -19,6 +24,14 @@ public function newLinesWritten(): int return $this->newLinesWritten; } + /** + * Ignore incoming new lines, keeping the previous $newLinesWritten value. + */ + public function ignoreNewLines(bool $shouldIgnore = true): void + { + $this->ignoreNewLines = $shouldIgnore; + } + /** * Write the output and capture the number of trailing new lines. */ @@ -30,6 +43,10 @@ protected function doWrite(string $message, bool $newline): void $message .= \PHP_EOL; } + if ($this->ignoreNewLines) { + return; + } + $trailingNewLines = strlen($message) - strlen(rtrim($message, \PHP_EOL)); if (trim($message) === '') { diff --git a/src/Spinner.php b/src/Spinner.php index 7e1f73f0..1862bfe8 100644 --- a/src/Spinner.php +++ b/src/Spinner.php @@ -41,6 +41,7 @@ public function __construct(public string $message = '') public function spin(Closure $callback): mixed { $this->capturePreviousNewLines(); + $this->ignoreNewLines(true); register_shutdown_function(fn () => $this->restoreCursor()); @@ -94,6 +95,18 @@ protected function resetTerminal(bool $originalAsync): void $this->eraseRenderedLines(); $this->showCursor(); + $this->ignoreNewLines(false); + } + + /** + * If the method exists, instruct the output to ignore new lines + * as the spinner will erase itself at the end of the process. + */ + protected function ignoreNewLines(bool $ignore = true): void + { + if (method_exists(static::output(), 'ignoreNewLines')) { + static::output()->ignoreNewLines($ignore); + } } /**