Skip to content

Commit

Permalink
Merge pull request #3175 from michalsn/cli_color
Browse files Browse the repository at this point in the history
Fix for multicolored strings in CLI
  • Loading branch information
michalsn authored Jun 28, 2020
2 parents 275ee07 + 0571de7 commit de968b7
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
30 changes: 30 additions & 0 deletions system/CLI/CLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,36 @@ public static function color(string $text, string $foreground, string $backgroun
$string .= "\033[4m";
}

// Detect if color method was already in use with this text
if (strpos($text, "\033[0m") !== false)
{
// Split the text into parts so that we can see
// if any part missing the color definition
$chunks = mb_split("\\033\[0m", $text);
// Reset text
$text = '';

foreach ($chunks as $chunk)
{
if ($chunk === '')
{
continue;
}

// If chunk doesn't have colors defined we need to add them
if (strpos($chunk, "\033[") === false)
{
$chunk = static::color($chunk, $foreground, $background, $format);
// Add color reset before chunk and clear end of the string
$text .= rtrim("\033[0m" . $chunk, "\033[0m");
}
else
{
$text .= $chunk;
}
}
}

return $string . ($text . "\033[0m");
}

Expand Down
14 changes: 14 additions & 0 deletions tests/system/CLI/CLITest.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,20 @@ public function testWriteForeground()
$this->assertEquals($expected, CITestStreamFilter::$buffer);
}

public function testWriteForegroundWithColorBefore()
{
CLI::write(CLI::color('green', 'green') . ' red', 'red');
$expected = "\033[0;31m\033[0;32mgreen\033[0m\033[0;31m red\033[0m" . PHP_EOL;
$this->assertEquals($expected, CITestStreamFilter::$buffer);
}

public function testWriteForegroundWithColorAfter()
{
CLI::write('red ' . CLI::color('green', 'green'), 'red');
$expected = "\033[0;31mred \033[0;32mgreen\033[0m" . PHP_EOL;
$this->assertEquals($expected, CITestStreamFilter::$buffer);
}

public function testWriteBackground()
{
CLI::write('test', 'red', 'green');
Expand Down

0 comments on commit de968b7

Please sign in to comment.