4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console\Helper;
14 use Symfony\Component\Console\Output\OutputInterface;
15 use Symfony\Component\Console\Exception\InvalidArgumentException;
18 * Provides helpers to display a table.
20 * @author Fabien Potencier <fabien@symfony.com>
21 * @author Саша Стаменковић <umpirsky@gmail.com>
22 * @author Abdellatif Ait boudad <a.aitboudad@gmail.com>
23 * @author Max Grigorian <maxakawizard@gmail.com>
32 private $headers = array();
39 private $rows = array();
42 * Column widths cache.
46 private $columnWidths = array();
49 * Number of columns cache.
53 private $numberOfColumns;
56 * @var OutputInterface
68 private $columnStyles = array();
70 private static $styles;
72 public function __construct(OutputInterface $output)
74 $this->output = $output;
77 self::$styles = self::initStyles();
80 $this->setStyle('default');
84 * Sets a style definition.
86 * @param string $name The style name
87 * @param TableStyle $style A TableStyle instance
89 public static function setStyleDefinition($name, TableStyle $style)
92 self::$styles = self::initStyles();
95 self::$styles[$name] = $style;
99 * Gets a style definition by name.
101 * @param string $name The style name
105 public static function getStyleDefinition($name)
107 if (!self::$styles) {
108 self::$styles = self::initStyles();
111 if (isset(self::$styles[$name])) {
112 return self::$styles[$name];
115 throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
121 * @param TableStyle|string $name The style name or a TableStyle instance
125 public function setStyle($name)
127 $this->style = $this->resolveStyle($name);
133 * Gets the current table style.
137 public function getStyle()
143 * Sets table column style.
145 * @param int $columnIndex Column index
146 * @param TableStyle|string $name The style name or a TableStyle instance
150 public function setColumnStyle($columnIndex, $name)
152 $columnIndex = (int) $columnIndex;
154 $this->columnStyles[$columnIndex] = $this->resolveStyle($name);
160 * Gets the current style for a column.
162 * If style was not set, it returns the global table style.
164 * @param int $columnIndex Column index
168 public function getColumnStyle($columnIndex)
170 if (isset($this->columnStyles[$columnIndex])) {
171 return $this->columnStyles[$columnIndex];
174 return $this->getStyle();
177 public function setHeaders(array $headers)
179 $headers = array_values($headers);
180 if (!empty($headers) && !is_array($headers[0])) {
181 $headers = array($headers);
184 $this->headers = $headers;
189 public function setRows(array $rows)
191 $this->rows = array();
193 return $this->addRows($rows);
196 public function addRows(array $rows)
198 foreach ($rows as $row) {
205 public function addRow($row)
207 if ($row instanceof TableSeparator) {
208 $this->rows[] = $row;
213 if (!is_array($row)) {
214 throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.');
217 $this->rows[] = array_values($row);
222 public function setRow($column, array $row)
224 $this->rows[$column] = $row;
230 * Renders table to output.
233 * +---------------+-----------------------+------------------+
234 * | ISBN | Title | Author |
235 * +---------------+-----------------------+------------------+
236 * | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
237 * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
238 * | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
239 * +---------------+-----------------------+------------------+
241 public function render()
243 $this->calculateNumberOfColumns();
244 $rows = $this->buildTableRows($this->rows);
245 $headers = $this->buildTableRows($this->headers);
247 $this->calculateColumnsWidth(array_merge($headers, $rows));
249 $this->renderRowSeparator();
250 if (!empty($headers)) {
251 foreach ($headers as $header) {
252 $this->renderRow($header, $this->style->getCellHeaderFormat());
253 $this->renderRowSeparator();
256 foreach ($rows as $row) {
257 if ($row instanceof TableSeparator) {
258 $this->renderRowSeparator();
260 $this->renderRow($row, $this->style->getCellRowFormat());
264 $this->renderRowSeparator();
271 * Renders horizontal header separator.
273 * Example: +-----+-----------+-------+
275 private function renderRowSeparator()
277 if (0 === $count = $this->numberOfColumns) {
281 if (!$this->style->getHorizontalBorderChar() && !$this->style->getCrossingChar()) {
285 $markup = $this->style->getCrossingChar();
286 for ($column = 0; $column < $count; ++$column) {
287 $markup .= str_repeat($this->style->getHorizontalBorderChar(), $this->columnWidths[$column]).$this->style->getCrossingChar();
290 $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
294 * Renders vertical column separator.
296 private function renderColumnSeparator()
298 return sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar());
304 * Example: | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
307 * @param string $cellFormat
309 private function renderRow(array $row, $cellFormat)
315 $rowContent = $this->renderColumnSeparator();
316 foreach ($this->getRowColumns($row) as $column) {
317 $rowContent .= $this->renderCell($row, $column, $cellFormat);
318 $rowContent .= $this->renderColumnSeparator();
320 $this->output->writeln($rowContent);
324 * Renders table cell with padding.
328 * @param string $cellFormat
330 private function renderCell(array $row, $column, $cellFormat)
332 $cell = isset($row[$column]) ? $row[$column] : '';
333 $width = $this->columnWidths[$column];
334 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
335 // add the width of the following columns(numbers of colspan).
336 foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
337 $width += $this->getColumnSeparatorWidth() + $this->columnWidths[$nextColumn];
341 // str_pad won't work properly with multi-byte strings, we need to fix the padding
342 if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
343 $width += strlen($cell) - mb_strwidth($cell, $encoding);
346 $style = $this->getColumnStyle($column);
348 if ($cell instanceof TableSeparator) {
349 return sprintf($style->getBorderFormat(), str_repeat($style->getHorizontalBorderChar(), $width));
352 $width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
353 $content = sprintf($style->getCellRowContentFormat(), $cell);
355 return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType()));
359 * Calculate number of columns for this table.
361 private function calculateNumberOfColumns()
363 if (null !== $this->numberOfColumns) {
368 foreach (array_merge($this->headers, $this->rows) as $row) {
369 if ($row instanceof TableSeparator) {
373 $columns[] = $this->getNumberOfColumns($row);
376 $this->numberOfColumns = max($columns);
379 private function buildTableRows($rows)
381 $unmergedRows = array();
382 for ($rowKey = 0; $rowKey < count($rows); ++$rowKey) {
383 $rows = $this->fillNextRows($rows, $rowKey);
385 // Remove any new line breaks and replace it with a new line
386 foreach ($rows[$rowKey] as $column => $cell) {
387 if (!strstr($cell, "\n")) {
390 $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
391 foreach ($lines as $lineKey => $line) {
392 if ($cell instanceof TableCell) {
393 $line = new TableCell($line, array('colspan' => $cell->getColspan()));
395 if (0 === $lineKey) {
396 $rows[$rowKey][$column] = $line;
398 $unmergedRows[$rowKey][$lineKey][$column] = $line;
404 $tableRows = array();
405 foreach ($rows as $rowKey => $row) {
406 $tableRows[] = $this->fillCells($row);
407 if (isset($unmergedRows[$rowKey])) {
408 $tableRows = array_merge($tableRows, $unmergedRows[$rowKey]);
416 * fill rows that contains rowspan > 1.
423 private function fillNextRows($rows, $line)
425 $unmergedRows = array();
426 foreach ($rows[$line] as $column => $cell) {
427 if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
428 $nbLines = $cell->getRowspan() - 1;
429 $lines = array($cell);
430 if (strstr($cell, "\n")) {
431 $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
432 $nbLines = count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
434 $rows[$line][$column] = new TableCell($lines[0], array('colspan' => $cell->getColspan()));
438 // create a two dimensional array (rowspan x colspan)
439 $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, array()), $unmergedRows);
440 foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
441 $value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
442 $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, array('colspan' => $cell->getColspan()));
443 if ($nbLines === $unmergedRowKey - $line) {
450 foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
451 // we need to know if $unmergedRow will be merged or inserted into $rows
452 if (isset($rows[$unmergedRowKey]) && is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
453 foreach ($unmergedRow as $cellKey => $cell) {
454 // insert cell into row at cellKey position
455 array_splice($rows[$unmergedRowKey], $cellKey, 0, array($cell));
458 $row = $this->copyRow($rows, $unmergedRowKey - 1);
459 foreach ($unmergedRow as $column => $cell) {
461 $row[$column] = $unmergedRow[$column];
464 array_splice($rows, $unmergedRowKey, 0, array($row));
472 * fill cells for a row that contains colspan > 1.
478 private function fillCells($row)
481 foreach ($row as $column => $cell) {
483 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
484 foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
485 // insert empty value at column position
491 return $newRow ?: $row;
500 private function copyRow($rows, $line)
503 foreach ($row as $cellKey => $cellValue) {
505 if ($cellValue instanceof TableCell) {
506 $row[$cellKey] = new TableCell('', array('colspan' => $cellValue->getColspan()));
514 * Gets number of columns by row.
520 private function getNumberOfColumns(array $row)
522 $columns = count($row);
523 foreach ($row as $column) {
524 $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
531 * Gets list of columns for the given row.
537 private function getRowColumns($row)
539 $columns = range(0, $this->numberOfColumns - 1);
540 foreach ($row as $cellKey => $cell) {
541 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
542 // exclude grouped columns.
543 $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
551 * Calculates columns widths.
555 private function calculateColumnsWidth($rows)
557 for ($column = 0; $column < $this->numberOfColumns; ++$column) {
559 foreach ($rows as $row) {
560 if ($row instanceof TableSeparator) {
564 foreach ($row as $i => $cell) {
565 if ($cell instanceof TableCell) {
566 $textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
567 $textLength = Helper::strlen($textContent);
568 if ($textLength > 0) {
569 $contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
570 foreach ($contentColumns as $position => $content) {
571 $row[$i + $position] = $content;
577 $lengths[] = $this->getCellWidth($row, $column);
580 $this->columnWidths[$column] = max($lengths) + strlen($this->style->getCellRowContentFormat()) - 2;
589 private function getColumnSeparatorWidth()
591 return strlen(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
602 private function getCellWidth(array $row, $column)
604 if (isset($row[$column])) {
605 $cell = $row[$column];
606 $cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
615 * Called after rendering to cleanup cache data.
617 private function cleanup()
619 $this->columnWidths = array();
620 $this->numberOfColumns = null;
623 private static function initStyles()
625 $borderless = new TableStyle();
627 ->setHorizontalBorderChar('=')
628 ->setVerticalBorderChar(' ')
629 ->setCrossingChar(' ')
632 $compact = new TableStyle();
634 ->setHorizontalBorderChar('')
635 ->setVerticalBorderChar(' ')
636 ->setCrossingChar('')
637 ->setCellRowContentFormat('%s')
640 $styleGuide = new TableStyle();
642 ->setHorizontalBorderChar('-')
643 ->setVerticalBorderChar(' ')
644 ->setCrossingChar(' ')
645 ->setCellHeaderFormat('%s')
649 'default' => new TableStyle(),
650 'borderless' => $borderless,
651 'compact' => $compact,
652 'symfony-style-guide' => $styleGuide,
656 private function resolveStyle($name)
658 if ($name instanceof TableStyle) {
662 if (isset(self::$styles[$name])) {
663 return self::$styles[$name];
666 throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));