From 6378c037adfa53465cce716edcd9464caac5104d Mon Sep 17 00:00:00 2001 From: Ricardo Boss Date: Tue, 12 Apr 2022 11:28:46 +0200 Subject: [PATCH] Added option to disable borders of table and added strip helper to determine visible column widths --- src/Console.php | 45 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/src/Console.php b/src/Console.php index 2f73f38..62701bf 100644 --- a/src/Console.php +++ b/src/Console.php @@ -215,11 +215,18 @@ public static function emergency(string $message, ...$args): void self::writeln("[EGY] " . vsprintf($message, $args), null, 'red', ['bold', 'underscore'], true); } + public static function strip(string $formattedMessage): string + { + $pattern = sprintf(preg_quote(self::$colorFormat, '/'), '.*?'); + + return preg_replace('/' . $pattern . '/', '', $formattedMessage); + } + /** * @param iterable> $data * @return iterable */ - public static function table(iterable $data, bool $ascii = false, bool $compact = false, string $borderColor = 'gray'): iterable + public static function table(iterable $data, bool $ascii = false, bool $compact = false, bool $noBorder = false, string $borderColor = 'gray'): iterable { if (!is_array($data)) { $rows = []; @@ -243,7 +250,7 @@ public static function table(iterable $data, bool $ascii = false, bool $compact }, []); $columnWidths = array_map(static function (array $column): int { - return max(array_map('strlen', $column)); + return max(array_map('mb_strlen', array_map([self::class, 'strip'], $column))); }, $columns); $hsep = $ascii ? '-' : '─'; @@ -295,26 +302,44 @@ public static function table(iterable $data, bool $ascii = false, bool $compact }; $header = array_shift($rows); - yield $printSeparator(top: true); + if (!$noBorder) { + yield $printSeparator(top: true); + } + $output = ''; foreach ($header as $key => $value) { - $output .= $vsep . ' ' . str_pad($value, $columnWidths[$key], ' ', STR_PAD_RIGHT) . ' '; + if (!$noBorder) { + $output .= $vsep . ' '; + } + $output .= str_pad($value, $columnWidths[$key], ' ', STR_PAD_RIGHT) . ' '; + } + + if ($noBorder) { + yield $output; + } else { + yield $output . $vsep; + yield $printSeparator(header: true); } - yield $output . $vsep; - yield $printSeparator(header: true); $rowCount = count($rows); foreach ($rows as $i => $row) { $output = ""; foreach ($row as $key => $value) { - $output .= $vsep . ' ' . str_pad($value, $columnWidths[$key], ' ', STR_PAD_RIGHT) . ' '; + if (!$noBorder) { + $output .= $vsep . ' '; + } + $output .= str_pad($value, $columnWidths[$key], ' ', STR_PAD_RIGHT) . ' '; + } + + if ($noBorder) { + yield $output; + } else { + yield $output . $vsep; } - $output .= $vsep; - yield $output; $lastLine = $i === $rowCount - 1; - if ($lastLine || !$compact) { + if (!$noBorder && ($lastLine || !$compact)) { yield $printSeparator(bottom: $lastLine); } }