From 1ebfcda70331fb801a2b421ca7f356218fe0bfb7 Mon Sep 17 00:00:00 2001 From: Natan Felles Date: Fri, 16 Nov 2018 02:22:33 -0200 Subject: [PATCH] Add CLI::strlen() --- system/CLI/CLI.php | 33 ++++++++++++++++++++++++++++++--- tests/system/CLI/CLITest.php | 6 ++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/system/CLI/CLI.php b/system/CLI/CLI.php index 16d7aa2a84d8..0f189be8981b 100644 --- a/system/CLI/CLI.php +++ b/system/CLI/CLI.php @@ -474,6 +474,33 @@ public static function color(string $text, string $foreground, string $backgroun //-------------------------------------------------------------------- + /** + * Get the number of characters in string having encoded characters + * and ignores styles set by the color() function + * + * @param string $string + * + * @return integer + */ + public static function strlen(string $string): int + { + foreach (static::$foreground_colors as $color) + { + $string = strtr($string, ["\033[" . $color . 'm' => '']); + } + + foreach (static::$background_colors as $color) + { + $string = strtr($string, ["\033[" . $color . 'm' => '']); + } + + $string = strtr($string, ["\033[4m" => '', "\033[0m" => '']); + + return mb_strlen($string); + } + + //-------------------------------------------------------------------- + /** * Attempts to determine the width of the viewable CLI window. * This only works on *nix-based systems, so return a sane default @@ -833,7 +860,7 @@ public static function table(array $tbody, array $thead = []) foreach ($table_rows[$row] as $col) { // Sets the size of this column in the current row - $all_cols_lengths[$row][$column] = mb_strlen($col); + $all_cols_lengths[$row][$column] = static::strlen($col); // If the current column does not have a value among the larger ones // or the value of this is greater than the existing one @@ -855,7 +882,7 @@ public static function table(array $tbody, array $thead = []) $column = 0; foreach ($table_rows[$row] as $col) { - $diff = $max_cols_lengths[$column] - mb_strlen($col); + $diff = $max_cols_lengths[$column] - static::strlen($col); if ($diff) { $table_rows[$row][$column] = $table_rows[$row][$column] . str_repeat(' ', $diff); @@ -875,7 +902,7 @@ public static function table(array $tbody, array $thead = []) $cols = '+'; foreach ($table_rows[$row] as $col) { - $cols .= str_repeat('-', mb_strlen($col) + 2) . '+'; + $cols .= str_repeat('-', static::strlen($col) + 2) . '+'; } $table .= $cols . PHP_EOL; } diff --git a/tests/system/CLI/CLITest.php b/tests/system/CLI/CLITest.php index 8093d912594f..2d812e107f30 100644 --- a/tests/system/CLI/CLITest.php +++ b/tests/system/CLI/CLITest.php @@ -377,4 +377,10 @@ public function tableProvider() ], ]; } + + public function testStrlen() + { + $this->assertEquals(18, mb_strlen(CLI::color('success', 'green'))); + $this->assertEquals(7, CLI::strlen(CLI::color('success', 'green'))); + } }