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>
30 private $headers = array();
35 private $rows = array();
38 * Column widths cache.
40 private $effectiveColumnWidths = array();
43 * Number of columns cache.
47 private $numberOfColumns;
50 * @var OutputInterface
62 private $columnStyles = array();
65 * User set column widths.
69 private $columnWidths = array();
71 private static $styles;
73 public function __construct(OutputInterface $output)
75 $this->output = $output;
78 self::$styles = self::initStyles();
81 $this->setStyle('default');
85 * Sets a style definition.
87 * @param string $name The style name
88 * @param TableStyle $style A TableStyle instance
90 public static function setStyleDefinition($name, TableStyle $style)
93 self::$styles = self::initStyles();
96 self::$styles[$name] = $style;
100 * Gets a style definition by name.
102 * @param string $name The style name
106 public static function getStyleDefinition($name)
108 if (!self::$styles) {
109 self::$styles = self::initStyles();
112 if (isset(self::$styles[$name])) {
113 return self::$styles[$name];
116 throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
122 * @param TableStyle|string $name The style name or a TableStyle instance
126 public function setStyle($name)
128 $this->style = $this->resolveStyle($name);
134 * Gets the current table style.
138 public function getStyle()
144 * Sets table column style.
146 * @param int $columnIndex Column index
147 * @param TableStyle|string $name The style name or a TableStyle instance
151 public function setColumnStyle($columnIndex, $name)
153 $columnIndex = (int) $columnIndex;
155 $this->columnStyles[$columnIndex] = $this->resolveStyle($name);
161 * Gets the current style for a column.
163 * If style was not set, it returns the global table style.
165 * @param int $columnIndex Column index
169 public function getColumnStyle($columnIndex)
171 if (isset($this->columnStyles[$columnIndex])) {
172 return $this->columnStyles[$columnIndex];
175 return $this->getStyle();
179 * Sets the minimum width of a column.
181 * @param int $columnIndex Column index
182 * @param int $width Minimum column width in characters
186 public function setColumnWidth($columnIndex, $width)
188 $this->columnWidths[(int) $columnIndex] = (int) $width;
194 * Sets the minimum width of all columns.
196 * @param array $widths
200 public function setColumnWidths(array $widths)
202 $this->columnWidths = array();
203 foreach ($widths as $index => $width) {
204 $this->setColumnWidth($index, $width);
210 public function setHeaders(array $headers)
212 $headers = array_values($headers);
213 if (!empty($headers) && !is_array($headers[0])) {
214 $headers = array($headers);
217 $this->headers = $headers;
222 public function setRows(array $rows)
224 $this->rows = array();
226 return $this->addRows($rows);
229 public function addRows(array $rows)
231 foreach ($rows as $row) {
238 public function addRow($row)
240 if ($row instanceof TableSeparator) {
241 $this->rows[] = $row;
246 if (!is_array($row)) {
247 throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.');
250 $this->rows[] = array_values($row);
255 public function setRow($column, array $row)
257 $this->rows[$column] = $row;
263 * Renders table to output.
267 * +---------------+-----------------------+------------------+
268 * | ISBN | Title | Author |
269 * +---------------+-----------------------+------------------+
270 * | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
271 * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
272 * | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
273 * +---------------+-----------------------+------------------+
276 public function render()
278 $this->calculateNumberOfColumns();
279 $rows = $this->buildTableRows($this->rows);
280 $headers = $this->buildTableRows($this->headers);
282 $this->calculateColumnsWidth(array_merge($headers, $rows));
284 $this->renderRowSeparator();
285 if (!empty($headers)) {
286 foreach ($headers as $header) {
287 $this->renderRow($header, $this->style->getCellHeaderFormat());
288 $this->renderRowSeparator();
291 foreach ($rows as $row) {
292 if ($row instanceof TableSeparator) {
293 $this->renderRowSeparator();
295 $this->renderRow($row, $this->style->getCellRowFormat());
299 $this->renderRowSeparator();
306 * Renders horizontal header separator.
308 * Example: <code>+-----+-----------+-------+</code>
310 private function renderRowSeparator()
312 if (0 === $count = $this->numberOfColumns) {
316 if (!$this->style->getHorizontalBorderChar() && !$this->style->getCrossingChar()) {
320 $markup = $this->style->getCrossingChar();
321 for ($column = 0; $column < $count; ++$column) {
322 $markup .= str_repeat($this->style->getHorizontalBorderChar(), $this->effectiveColumnWidths[$column]).$this->style->getCrossingChar();
325 $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
329 * Renders vertical column separator.
331 private function renderColumnSeparator()
333 return sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar());
339 * Example: <code>| 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |</code>
342 * @param string $cellFormat
344 private function renderRow(array $row, $cellFormat)
350 $rowContent = $this->renderColumnSeparator();
351 foreach ($this->getRowColumns($row) as $column) {
352 $rowContent .= $this->renderCell($row, $column, $cellFormat);
353 $rowContent .= $this->renderColumnSeparator();
355 $this->output->writeln($rowContent);
359 * Renders table cell with padding.
363 * @param string $cellFormat
365 private function renderCell(array $row, $column, $cellFormat)
367 $cell = isset($row[$column]) ? $row[$column] : '';
368 $width = $this->effectiveColumnWidths[$column];
369 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
370 // add the width of the following columns(numbers of colspan).
371 foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
372 $width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn];
376 // str_pad won't work properly with multi-byte strings, we need to fix the padding
377 if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
378 $width += strlen($cell) - mb_strwidth($cell, $encoding);
381 $style = $this->getColumnStyle($column);
383 if ($cell instanceof TableSeparator) {
384 return sprintf($style->getBorderFormat(), str_repeat($style->getHorizontalBorderChar(), $width));
387 $width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
388 $content = sprintf($style->getCellRowContentFormat(), $cell);
390 return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType()));
394 * Calculate number of columns for this table.
396 private function calculateNumberOfColumns()
398 if (null !== $this->numberOfColumns) {
403 foreach (array_merge($this->headers, $this->rows) as $row) {
404 if ($row instanceof TableSeparator) {
408 $columns[] = $this->getNumberOfColumns($row);
411 $this->numberOfColumns = max($columns);
414 private function buildTableRows($rows)
416 $unmergedRows = array();
417 for ($rowKey = 0; $rowKey < count($rows); ++$rowKey) {
418 $rows = $this->fillNextRows($rows, $rowKey);
420 // Remove any new line breaks and replace it with a new line
421 foreach ($rows[$rowKey] as $column => $cell) {
422 if (!strstr($cell, "\n")) {
425 $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
426 foreach ($lines as $lineKey => $line) {
427 if ($cell instanceof TableCell) {
428 $line = new TableCell($line, array('colspan' => $cell->getColspan()));
430 if (0 === $lineKey) {
431 $rows[$rowKey][$column] = $line;
433 $unmergedRows[$rowKey][$lineKey][$column] = $line;
439 $tableRows = array();
440 foreach ($rows as $rowKey => $row) {
441 $tableRows[] = $this->fillCells($row);
442 if (isset($unmergedRows[$rowKey])) {
443 $tableRows = array_merge($tableRows, $unmergedRows[$rowKey]);
451 * fill rows that contains rowspan > 1.
458 * @throws InvalidArgumentException
460 private function fillNextRows(array $rows, $line)
462 $unmergedRows = array();
463 foreach ($rows[$line] as $column => $cell) {
464 if (null !== $cell && !$cell instanceof TableCell && !is_scalar($cell) && !(is_object($cell) && method_exists($cell, '__toString'))) {
465 throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing __toString, %s given.', gettype($cell)));
467 if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
468 $nbLines = $cell->getRowspan() - 1;
469 $lines = array($cell);
470 if (strstr($cell, "\n")) {
471 $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
472 $nbLines = count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
474 $rows[$line][$column] = new TableCell($lines[0], array('colspan' => $cell->getColspan()));
478 // create a two dimensional array (rowspan x colspan)
479 $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, array()), $unmergedRows);
480 foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
481 $value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
482 $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, array('colspan' => $cell->getColspan()));
483 if ($nbLines === $unmergedRowKey - $line) {
490 foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
491 // we need to know if $unmergedRow will be merged or inserted into $rows
492 if (isset($rows[$unmergedRowKey]) && is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
493 foreach ($unmergedRow as $cellKey => $cell) {
494 // insert cell into row at cellKey position
495 array_splice($rows[$unmergedRowKey], $cellKey, 0, array($cell));
498 $row = $this->copyRow($rows, $unmergedRowKey - 1);
499 foreach ($unmergedRow as $column => $cell) {
501 $row[$column] = $unmergedRow[$column];
504 array_splice($rows, $unmergedRowKey, 0, array($row));
512 * fill cells for a row that contains colspan > 1.
516 private function fillCells($row)
519 foreach ($row as $column => $cell) {
521 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
522 foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
523 // insert empty value at column position
529 return $newRow ?: $row;
538 private function copyRow(array $rows, $line)
541 foreach ($row as $cellKey => $cellValue) {
543 if ($cellValue instanceof TableCell) {
544 $row[$cellKey] = new TableCell('', array('colspan' => $cellValue->getColspan()));
552 * Gets number of columns by row.
556 private function getNumberOfColumns(array $row)
558 $columns = count($row);
559 foreach ($row as $column) {
560 $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
567 * Gets list of columns for the given row.
571 private function getRowColumns(array $row)
573 $columns = range(0, $this->numberOfColumns - 1);
574 foreach ($row as $cellKey => $cell) {
575 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
576 // exclude grouped columns.
577 $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
585 * Calculates columns widths.
587 private function calculateColumnsWidth(array $rows)
589 for ($column = 0; $column < $this->numberOfColumns; ++$column) {
591 foreach ($rows as $row) {
592 if ($row instanceof TableSeparator) {
596 foreach ($row as $i => $cell) {
597 if ($cell instanceof TableCell) {
598 $textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
599 $textLength = Helper::strlen($textContent);
600 if ($textLength > 0) {
601 $contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
602 foreach ($contentColumns as $position => $content) {
603 $row[$i + $position] = $content;
609 $lengths[] = $this->getCellWidth($row, $column);
612 $this->effectiveColumnWidths[$column] = max($lengths) + strlen($this->style->getCellRowContentFormat()) - 2;
621 private function getColumnSeparatorWidth()
623 return strlen(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
634 private function getCellWidth(array $row, $column)
638 if (isset($row[$column])) {
639 $cell = $row[$column];
640 $cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
643 $columnWidth = isset($this->columnWidths[$column]) ? $this->columnWidths[$column] : 0;
645 return max($cellWidth, $columnWidth);
649 * Called after rendering to cleanup cache data.
651 private function cleanup()
653 $this->effectiveColumnWidths = array();
654 $this->numberOfColumns = null;
657 private static function initStyles()
659 $borderless = new TableStyle();
661 ->setHorizontalBorderChar('=')
662 ->setVerticalBorderChar(' ')
663 ->setCrossingChar(' ')
666 $compact = new TableStyle();
668 ->setHorizontalBorderChar('')
669 ->setVerticalBorderChar(' ')
670 ->setCrossingChar('')
671 ->setCellRowContentFormat('%s')
674 $styleGuide = new TableStyle();
676 ->setHorizontalBorderChar('-')
677 ->setVerticalBorderChar(' ')
678 ->setCrossingChar(' ')
679 ->setCellHeaderFormat('%s')
683 'default' => new TableStyle(),
684 'borderless' => $borderless,
685 'compact' => $compact,
686 'symfony-style-guide' => $styleGuide,
690 private function resolveStyle($name)
692 if ($name instanceof TableStyle) {
696 if (isset(self::$styles[$name])) {
697 return self::$styles[$name];
700 throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));