Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Colorize one cell of table #107

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 60 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -609,12 +609,70 @@ $writer->table([
'head' => 'boldGreen', // For the table heading
'odd' => 'bold', // For the odd rows (1st row is odd, then 3, 5 etc)
'even' => 'comment', // For the even rows (2nd row is even, then 4, 6 etc)
'1:1' => 'red', // For cell in row 1 col 1 (1 based count, 'apple' in this example)
'2:*' => '', // For all cells in row 2 (1 based count)
'*:2' => '', // For all cells in col 2 (1 based count)
'b-c' => '', // For all columns named 'b-c' (same as '*:2' in this example)
'*:*' => 'blue', // For all cells in table (Set all cells to blue)
]);
```

You can define the style of a cell dynamically using a callback. You could then apply one style or another depending on a value.

```php
$rows = [
['name' => 'John Doe', 'age' => '30'],
['name' => 'Jane Smith', 'age' => '25'],
['name' => 'Bob Johnson', 'age' => '40'],
];

// 'head', 'odd', 'even' are all the styles for now
// In future we may support styling a column by its name!
$styles = [
'*:2' => function ($val, $row) {
return $row['age'] >= 30 ? 'boldRed' : '';
},
];

$writer->table($rows, $styles);
```

The example above only processes the cells in the second column of the table. Yf you want to process any cell, you can use the `*:*` key. You could then customise each cell in the table

```php
$rows = [
['name' => 'John Doe', 'age' => '30'],
['name' => 'Jane Smith', 'age' => '25'],
['name' => 'Alice Bob', 'age' => '10'],
['name' => 'Big Johnson', 'age' => '40'],
['name' => 'Jane X', 'age' => '50'],
['name' => 'John Smith', 'age' => '20'],
['name' => 'Bob John', 'age' => '28'],
];

$styles = [
'*:*' => function ($val, $row) {
if ($val === 'Jane X') {
return 'yellow';
}
if ($val == 10 || $val == 20) {
return 'boldPurple';
}
if (str_contains($val, 'Bob')) {
return 'blue';
}
return $row['age'] >= 30 ? 'boldRed' : '';
},
];

$writer->table($rows, $styles);
```

> **Note: Priority in increasing order:**
> - `odd` or `even`
> - `2:*` (row)
> - `*:2` or `b-c <-> column name` (col)
> - `*:*` any cell in table
> - `1:1` (cell) = **highest priority**

#### Justify content (Display setting)

If you want to display certain configurations (from your .env file for example) a bit like Laravel does (via the `php artisan about` command) you can use the `justify` method.
Expand Down
74 changes: 66 additions & 8 deletions src/Output/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,27 +45,54 @@ public function render(array $rows, array $styles = []): string
[$head, $rows] = $table;

$styles = $this->normalizeStyles($styles);
$title = $body = $dash = [];
$title = $body = $dash = $positions = [];

[$start, $end] = $styles['head'];
$pos = 0;
foreach ($head as $col => $size) {
$dash[] = str_repeat('-', $size + 2);
$title[] = str_pad($this->toWords($col), $size, ' ');
$dash[] = str_repeat('-', $size + 2);
$title[] = str_pad($this->toWords($col), $size, ' ');
$positions[$col] = ++$pos;
}

$title = "|$start " . implode(" $end|$start ", $title) . " $end|" . PHP_EOL;

$odd = true;
foreach ($rows as $row) {
foreach ($rows as $line => $row) {
$parts = [];
$line++;

[$start, $end] = $styles[['even', 'odd'][(int) $odd]];
foreach ($head as $col => $size) {
$parts[] = str_pad($row[$col] ?? '', $size, ' ');
$colNumber = $positions[$col];

if (isset($styles[$line . ':' . $colNumber])) { // cell, 1:1
$style = $styles[$line . ':' . $colNumber];
} else if (isset($styles[$col]) || isset($styles['*:' . $colNumber])) { // col, *:2 or b
$style = $styles['*:' . $colNumber] ?? $styles[$col];
} else if (isset($styles[$line . ':*'])) { // row, 2:*
$style = $styles[$line . ':*'];
} else if (isset($styles['*:*'])) { // any cell, *:*
$style = $styles['*:*'];
} else {
$style = $styles[['even', 'odd'][(int) $odd]];
}

$text = $row[$col] ?? '';
[$start, $end] = $this->parseStyle($style, $text, $row, $rows);

if (preg_match('/(\\x1b(?:.+)m)/U', $text, $matches)) {
$word = str_replace($matches[1], '', $text);
$word = preg_replace('/\\x1b\[0m/', '', $word);

$size += strlen($text) - strlen($word);
}

$parts[] = "$start " . str_pad($text, $size, ' ') . " $end";
}

$odd = !$odd;
$body[] = "|$start " . implode(" $end|$start ", $parts) . " $end|";
$body[] = '|' . implode('|', $parts) . '|';
}

$dash = '+' . implode('+', $dash) . '+' . PHP_EOL;
Expand Down Expand Up @@ -93,7 +120,18 @@ protected function normalize(array $rows): array
}

foreach ($head as $col => &$value) {
$cols = array_column($rows, $col);
$cols = array_column($rows, $col);
$cols = array_map(function($col) {
$col ??= '';

if (preg_match('/(\\x1b(?:.+)m)/U', $col, $matches)) {
$col = str_replace($matches[1], '', $col);
$col = preg_replace('/\\x1b\[0m/', '', $col);
}

return $col;
}, $cols);

$span = array_map('strlen', $cols);
$span[] = strlen($col);
$value = max($span);
Expand All @@ -112,11 +150,31 @@ protected function normalizeStyles(array $styles): array
];

foreach ($styles as $for => $style) {
if (isset($default[$for])) {
if (is_string($style) && $style !== '') {
$default[$for] = ['<' . trim($style, '<> ') . '>', '</end>'];
} else if (str_contains($for, ':') && is_callable($style)) {
$default[$for] = $style;
}
}

return $default;
}

protected function parseStyle(array|callable $style, $val, array $row, array $table): array
{
if (is_array($style)) {
return $style;
}

$style = call_user_func($style, $val, $row, $table);

if (is_string($style) && $style !== '') {
return ['<' . trim($style, '<> ') . '>', '</end>'];
}
if (is_array($style) && count($style) === 2) {
return $style;
}

return ['', ''];
}
}
Loading
Loading