php-cli icon indicating copy to clipboard operation
php-cli copied to clipboard

Table rendering misalignment when using colored/formatted strings in Table component

Open acataluddi opened this issue 7 months ago • 2 comments

Hi Jitendra,

I've discovered a table rendering bug that occurs when using colored/formatted strings. Here's an example with a 2x2 table where values in the last column are in bold:

$rows = [
    ['Name' => 'Server A', 'Hostname' => '<bold>server-a.example.com</end>'],
    ['Name' => 'Server B', 'Hostname' => '<bold>server-b.example.com</end>'],
];

$this->app()->io()->writer()->colors((new Table())->render($rows));

The expected output should be:

+----------+----------------------------------+
| Name     | Hostname                         |
+----------+----------------------------------+
| Server A | server-a.example.com             |
| Server B | server-b.example.com             |
+----------+----------------------------------+

As a result, I get the following:

+----------+----------------------------------+
| Name     | Hostname                         |
+----------+----------------------------------+
| Server A | server-a.example.com |
| Server B | server-b.example.com |
+----------+----------------------------------+

I believe the formatting tags are included in the string length calculation but then removed without being replaced by trailing white spaces, as the number of missing characters exactly matches strlen('<bold></end>').

Kind regards,

Adriano

acataluddi avatar May 11 '25 09:05 acataluddi

Hi @acataluddi

Tables use a class that handles page layout autonomously. So, if you want to color table cells, you have to use the second parameter ($styles) of the table method of the Writer instance (or of the render method of the Table class instance).

You can rewrite your example this way:

$rows = [
    ['Name' => 'Server A', 'Hostname' => 'server-a.example.com'],
    ['Name' => 'Server B', 'Hostname' => 'server-b.example.com'],
];

$this->app()->io()->writer()->table($rows, [
  'Hostname' => 'bold'
]);

See https://github.com/adhocore/php-cli?tab=readme-ov-file#tables

Image

dimtrovich avatar May 13 '25 17:05 dimtrovich

hi @dimtrovich 😄

adhocore avatar May 14 '25 12:05 adhocore