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 $effectiveColumnWidths = array();
49 * Number of columns cache.
53 private $numberOfColumns;
56 * @var OutputInterface
68 private $columnStyles = array();
71 * User set column widths.
75 private $columnWidths = array();
77 private static $styles;
79 public function __construct(OutputInterface $output)
81 $this->output = $output;
84 self::$styles = self::initStyles();
87 $this->setStyle('default');
91 * Sets a style definition.
93 * @param string $name The style name
94 * @param TableStyle $style A TableStyle instance
96 public static function setStyleDefinition($name, TableStyle $style)
99 self::$styles = self::initStyles();
102 self::$styles[$name] = $style;
106 * Gets a style definition by name.
108 * @param string $name The style name
112 public static function getStyleDefinition($name)
114 if (!self::$styles) {
115 self::$styles = self::initStyles();
118 if (isset(self::$styles[$name])) {
119 return self::$styles[$name];
122 throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
128 * @param TableStyle|string $name The style name or a TableStyle instance
132 public function setStyle($name)
134 $this->style = $this->resolveStyle($name);
140 * Gets the current table style.
144 public function getStyle()
150 * Sets table column style.
152 * @param int $columnIndex Column index
153 * @param TableStyle|string $name The style name or a TableStyle instance
157 public function setColumnStyle($columnIndex, $name)
159 $columnIndex = (int) $columnIndex;
161 $this->columnStyles[$columnIndex] = $this->resolveStyle($name);
167 * Gets the current style for a column.
169 * If style was not set, it returns the global table style.
171 * @param int $columnIndex Column index
175 public function getColumnStyle($columnIndex)
177 if (isset($this->columnStyles[$columnIndex])) {
178 return $this->columnStyles[$columnIndex];
181 return $this->getStyle();
185 * Sets the minimum width of a column.
187 * @param int $columnIndex Column index
188 * @param int $width Minimum column width in characters
192 public function setColumnWidth($columnIndex, $width)
194 $this->columnWidths[(int) $columnIndex] = (int) $width;
200 * Sets the minimum width of all columns.
202 * @param array $widths
206 public function setColumnWidths(array $widths)
208 $this->columnWidths = array();
209 foreach ($widths as $index => $width) {
210 $this->setColumnWidth($index, $width);
216 public function setHeaders(array $headers)
218 $headers = array_values($headers);
219 if (!empty($headers) && !is_array($headers[0])) {
220 $headers = array($headers);
223 $this->headers = $headers;
228 public function setRows(array $rows)
230 $this->rows = array();
232 return $this->addRows($rows);
235 public function addRows(array $rows)
237 foreach ($rows as $row) {
244 public function addRow($row)
246 if ($row instanceof TableSeparator) {
247 $this->rows[] = $row;
252 if (!is_array($row)) {
253 throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.');
256 $this->rows[] = array_values($row);
261 public function setRow($column, array $row)
263 $this->rows[$column] = $row;
269 * Renders table to output.
272 * +---------------+-----------------------+------------------+
273 * | ISBN | Title | Author |
274 * +---------------+-----------------------+------------------+
275 * | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
276 * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
277 * | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
278 * +---------------+-----------------------+------------------+
280 public function render()
282 $this->calculateNumberOfColumns();
283 $rows = $this->buildTableRows($this->rows);
284 $headers = $this->buildTableRows($this->headers);
286 $this->calculateColumnsWidth(array_merge($headers, $rows));
288 $this->renderRowSeparator();
289 if (!empty($headers)) {
290 foreach ($headers as $header) {
291 $this->renderRow($header, $this->style->getCellHeaderFormat());
292 $this->renderRowSeparator();
295 foreach ($rows as $row) {
296 if ($row instanceof TableSeparator) {
297 $this->renderRowSeparator();
299 $this->renderRow($row, $this->style->getCellRowFormat());
303 $this->renderRowSeparator();
310 * Renders horizontal header separator.
312 * Example: +-----+-----------+-------+
314 private function renderRowSeparator()
316 if (0 === $count = $this->numberOfColumns) {
320 if (!$this->style->getHorizontalBorderChar() && !$this->style->getCrossingChar()) {
324 $markup = $this->style->getCrossingChar();
325 for ($column = 0; $column < $count; ++$column) {
326 $markup .= str_repeat($this->style->getHorizontalBorderChar(), $this->effectiveColumnWidths[$column]).$this->style->getCrossingChar();
329 $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
333 * Renders vertical column separator.
335 private function renderColumnSeparator()
337 return sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar());
343 * Example: | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
346 * @param string $cellFormat
348 private function renderRow(array $row, $cellFormat)
354 $rowContent = $this->renderColumnSeparator();
355 foreach ($this->getRowColumns($row) as $column) {
356 $rowContent .= $this->renderCell($row, $column, $cellFormat);
357 $rowContent .= $this->renderColumnSeparator();
359 $this->output->writeln($rowContent);
363 * Renders table cell with padding.
367 * @param string $cellFormat
369 private function renderCell(array $row, $column, $cellFormat)
371 $cell = isset($row[$column]) ? $row[$column] : '';
372 $width = $this->effectiveColumnWidths[$column];
373 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
374 // add the width of the following columns(numbers of colspan).
375 foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
376 $width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn];
380 // str_pad won't work properly with multi-byte strings, we need to fix the padding
381 if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
382 $width += strlen($cell) - mb_strwidth($cell, $encoding);
385 $style = $this->getColumnStyle($column);
387 if ($cell instanceof TableSeparator) {
388 return sprintf($style->getBorderFormat(), str_repeat($style->getHorizontalBorderChar(), $width));
391 $width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
392 $content = sprintf($style->getCellRowContentFormat(), $cell);
394 return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType()));
398 * Calculate number of columns for this table.
400 private function calculateNumberOfColumns()
402 if (null !== $this->numberOfColumns) {
407 foreach (array_merge($this->headers, $this->rows) as $row) {
408 if ($row instanceof TableSeparator) {
412 $columns[] = $this->getNumberOfColumns($row);
415 $this->numberOfColumns = max($columns);
418 private function buildTableRows($rows)
420 $unmergedRows = array();
421 for ($rowKey = 0; $rowKey < count($rows); ++$rowKey) {
422 $rows = $this->fillNextRows($rows, $rowKey);
424 // Remove any new line breaks and replace it with a new line
425 foreach ($rows[$rowKey] as $column => $cell) {
426 if (!strstr($cell, "\n")) {
429 $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
430 foreach ($lines as $lineKey => $line) {
431 if ($cell instanceof TableCell) {
432 $line = new TableCell($line, array('colspan' => $cell->getColspan()));
434 if (0 === $lineKey) {
435 $rows[$rowKey][$column] = $line;
437 $unmergedRows[$rowKey][$lineKey][$column] = $line;
443 $tableRows = array();
444 foreach ($rows as $rowKey => $row) {
445 $tableRows[] = $this->fillCells($row);
446 if (isset($unmergedRows[$rowKey])) {
447 $tableRows = array_merge($tableRows, $unmergedRows[$rowKey]);
455 * fill rows that contains rowspan > 1.
462 private function fillNextRows($rows, $line)
464 $unmergedRows = array();
465 foreach ($rows[$line] as $column => $cell) {
466 if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
467 $nbLines = $cell->getRowspan() - 1;
468 $lines = array($cell);
469 if (strstr($cell, "\n")) {
470 $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
471 $nbLines = count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
473 $rows[$line][$column] = new TableCell($lines[0], array('colspan' => $cell->getColspan()));
477 // create a two dimensional array (rowspan x colspan)
478 $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, array()), $unmergedRows);
479 foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
480 $value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
481 $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, array('colspan' => $cell->getColspan()));
482 if ($nbLines === $unmergedRowKey - $line) {
489 foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
490 // we need to know if $unmergedRow will be merged or inserted into $rows
491 if (isset($rows[$unmergedRowKey]) && is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
492 foreach ($unmergedRow as $cellKey => $cell) {
493 // insert cell into row at cellKey position
494 array_splice($rows[$unmergedRowKey], $cellKey, 0, array($cell));
497 $row = $this->copyRow($rows, $unmergedRowKey - 1);
498 foreach ($unmergedRow as $column => $cell) {
500 $row[$column] = $unmergedRow[$column];
503 array_splice($rows, $unmergedRowKey, 0, array($row));
511 * fill cells for a row that contains colspan > 1.
517 private function fillCells($row)
520 foreach ($row as $column => $cell) {
522 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
523 foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
524 // insert empty value at column position
530 return $newRow ?: $row;
539 private function copyRow($rows, $line)
542 foreach ($row as $cellKey => $cellValue) {
544 if ($cellValue instanceof TableCell) {
545 $row[$cellKey] = new TableCell('', array('colspan' => $cellValue->getColspan()));
553 * Gets number of columns by row.
559 private function getNumberOfColumns(array $row)
561 $columns = count($row);
562 foreach ($row as $column) {
563 $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
570 * Gets list of columns for the given row.
576 private function getRowColumns($row)
578 $columns = range(0, $this->numberOfColumns - 1);
579 foreach ($row as $cellKey => $cell) {
580 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
581 // exclude grouped columns.
582 $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
590 * Calculates columns widths.
594 private function calculateColumnsWidth($rows)
596 for ($column = 0; $column < $this->numberOfColumns; ++$column) {
598 foreach ($rows as $row) {
599 if ($row instanceof TableSeparator) {
603 foreach ($row as $i => $cell) {
604 if ($cell instanceof TableCell) {
605 $textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
606 $textLength = Helper::strlen($textContent);
607 if ($textLength > 0) {
608 $contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
609 foreach ($contentColumns as $position => $content) {
610 $row[$i + $position] = $content;
616 $lengths[] = $this->getCellWidth($row, $column);
619 $this->effectiveColumnWidths[$column] = max($lengths) + strlen($this->style->getCellRowContentFormat()) - 2;
628 private function getColumnSeparatorWidth()
630 return strlen(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
641 private function getCellWidth(array $row, $column)
645 if (isset($row[$column])) {
646 $cell = $row[$column];
647 $cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
650 $columnWidth = isset($this->columnWidths[$column]) ? $this->columnWidths[$column] : 0;
652 return max($cellWidth, $columnWidth);
656 * Called after rendering to cleanup cache data.
658 private function cleanup()
660 $this->effectiveColumnWidths = array();
661 $this->numberOfColumns = null;
664 private static function initStyles()
666 $borderless = new TableStyle();
668 ->setHorizontalBorderChar('=')
669 ->setVerticalBorderChar(' ')
670 ->setCrossingChar(' ')
673 $compact = new TableStyle();
675 ->setHorizontalBorderChar('')
676 ->setVerticalBorderChar(' ')
677 ->setCrossingChar('')
678 ->setCellRowContentFormat('%s')
681 $styleGuide = new TableStyle();
683 ->setHorizontalBorderChar('-')
684 ->setVerticalBorderChar(' ')
685 ->setCrossingChar(' ')
686 ->setCellHeaderFormat('%s')
690 'default' => new TableStyle(),
691 'borderless' => $borderless,
692 'compact' => $compact,
693 'symfony-style-guide' => $styleGuide,
697 private function resolveStyle($name)
699 if ($name instanceof TableStyle) {
703 if (isset(self::$styles[$name])) {
704 return self::$styles[$name];
707 throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));