Skip to content

Commit

Permalink
Added option to disable borders of table and added strip helper to de…
Browse files Browse the repository at this point in the history
…termine visible column widths
  • Loading branch information
ricardoboss committed Apr 12, 2022
1 parent 2e1d372 commit 6378c03
Showing 1 changed file with 35 additions and 10 deletions.
45 changes: 35 additions & 10 deletions src/Console.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<int, array<string, scalar>> $data
* @return iterable<int, string>
*/
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 = [];
Expand All @@ -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 ? '-' : '';
Expand Down Expand Up @@ -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);
}
}
Expand Down

0 comments on commit 6378c03

Please sign in to comment.