/** * Render a text table containing the data provided, that will fit inside console window's width. * * @param $data * @param $cols * @param $consoleWidth * @return string */ protected function renderTable($data, $cols, $consoleWidth) { $result = ''; $padding = 2; // If there is only 1 column, just concatenate it if ($cols == 1) { foreach ($data as $row) { $result .= $row[0] . "\n"; } return $result; } // Get the string wrapper supporting UTF-8 character encoding $strWrapper = StringUtils::getWrapper('UTF-8'); // Determine max width for each column $maxW = array(); for ($x = 1; $x <= $cols; $x += 1) { $maxW[$x] = 0; foreach ($data as $row) { $maxW[$x] = max($maxW[$x], $strWrapper->strlen($row[$x - 1]) + $padding * 2); } } /* * Check if the sum of x-1 columns fit inside console window width - 10 * chars. If columns do not fit inside console window, then we'll just * concatenate them and output as is. */ $width = 0; for ($x = 1; $x < $cols; $x += 1) { $width += $maxW[$x]; } if ($width >= $consoleWidth - 10) { foreach ($data as $row) { $result .= implode(" ", $row) . "\n"; } return $result; } /* * Use Zend\Text\Table to render the table. * The last column will use the remaining space in console window * (minus 1 character to prevent double wrapping at the edge of the * screen). */ $maxW[$cols] = $consoleWidth - $width - 1; $table = new Table\Table(); $table->setColumnWidths($maxW); $table->setDecorator(new Table\Decorator\Blank()); $table->setPadding(2); foreach ($data as $row) { $table->appendRow($row); } return $table->render(); }