diff --git a/system/CLI/CLI.php b/system/CLI/CLI.php index 174074277836..bd7b7b7b6b82 100644 --- a/system/CLI/CLI.php +++ b/system/CLI/CLI.php @@ -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"); } diff --git a/tests/system/CLI/CLITest.php b/tests/system/CLI/CLITest.php index 76f74e548a79..c954a77abd9f 100644 --- a/tests/system/CLI/CLITest.php +++ b/tests/system/CLI/CLITest.php @@ -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');