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\Exception\InvalidArgumentException;
15 use Symfony\Component\Console\Output\OutputInterface;
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 * +---------------+-----------------------+------------------+
275 public function render()
277 $this->calculateNumberOfColumns();
278 $rows = $this->buildTableRows($this->rows);
279 $headers = $this->buildTableRows($this->headers);
281 $this->calculateColumnsWidth(array_merge($headers, $rows));
283 $this->renderRowSeparator();
284 if (!empty($headers)) {
285 foreach ($headers as $header) {
286 $this->renderRow($header, $this->style->getCellHeaderFormat());
287 $this->renderRowSeparator();
290 foreach ($rows as $row) {
291 if ($row instanceof TableSeparator) {
292 $this->renderRowSeparator();
294 $this->renderRow($row, $this->style->getCellRowFormat());
298 $this->renderRowSeparator();
305 * Renders horizontal header separator.
309 * +-----+-----------+-------+
311 private function renderRowSeparator()
313 if (0 === $count = $this->numberOfColumns) {
317 if (!$this->style->getHorizontalBorderChar() && !$this->style->getCrossingChar()) {
321 $markup = $this->style->getCrossingChar();
322 for ($column = 0; $column < $count; ++$column) {
323 $markup .= str_repeat($this->style->getHorizontalBorderChar(), $this->effectiveColumnWidths[$column]).$this->style->getCrossingChar();
326 $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
330 * Renders vertical column separator.
332 private function renderColumnSeparator()
334 return sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar());
342 * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
345 * @param string $cellFormat
347 private function renderRow(array $row, $cellFormat)
353 $rowContent = $this->renderColumnSeparator();
354 foreach ($this->getRowColumns($row) as $column) {
355 $rowContent .= $this->renderCell($row, $column, $cellFormat);
356 $rowContent .= $this->renderColumnSeparator();
358 $this->output->writeln($rowContent);
362 * Renders table cell with padding.
366 * @param string $cellFormat
368 private function renderCell(array $row, $column, $cellFormat)
370 $cell = isset($row[$column]) ? $row[$column] : '';
371 $width = $this->effectiveColumnWidths[$column];
372 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
373 // add the width of the following columns(numbers of colspan).
374 foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
375 $width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn];
379 // str_pad won't work properly with multi-byte strings, we need to fix the padding
380 if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
381 $width += \strlen($cell) - mb_strwidth($cell, $encoding);
384 $style = $this->getColumnStyle($column);
386 if ($cell instanceof TableSeparator) {
387 return sprintf($style->getBorderFormat(), str_repeat($style->getHorizontalBorderChar(), $width));
390 $width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
391 $content = sprintf($style->getCellRowContentFormat(), $cell);
393 return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType()));
397 * Calculate number of columns for this table.
399 private function calculateNumberOfColumns()
401 if (null !== $this->numberOfColumns) {
406 foreach (array_merge($this->headers, $this->rows) as $row) {
407 if ($row instanceof TableSeparator) {
411 $columns[] = $this->getNumberOfColumns($row);
414 $this->numberOfColumns = max($columns);
417 private function buildTableRows($rows)
419 $unmergedRows = array();
420 for ($rowKey = 0; $rowKey < \count($rows); ++$rowKey) {
421 $rows = $this->fillNextRows($rows, $rowKey);
423 // Remove any new line breaks and replace it with a new line
424 foreach ($rows[$rowKey] as $column => $cell) {
425 if (!strstr($cell, "\n")) {
428 $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
429 foreach ($lines as $lineKey => $line) {
430 if ($cell instanceof TableCell) {
431 $line = new TableCell($line, array('colspan' => $cell->getColspan()));
433 if (0 === $lineKey) {
434 $rows[$rowKey][$column] = $line;
436 $unmergedRows[$rowKey][$lineKey][$column] = $line;
442 $tableRows = array();
443 foreach ($rows as $rowKey => $row) {
444 $tableRows[] = $this->fillCells($row);
445 if (isset($unmergedRows[$rowKey])) {
446 $tableRows = array_merge($tableRows, $unmergedRows[$rowKey]);
454 * fill rows that contains rowspan > 1.
461 * @throws InvalidArgumentException
463 private function fillNextRows(array $rows, $line)
465 $unmergedRows = array();
466 foreach ($rows[$line] as $column => $cell) {
467 if (null !== $cell && !$cell instanceof TableCell && !is_scalar($cell) && !(\is_object($cell) && method_exists($cell, '__toString'))) {
468 throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing __toString, %s given.', \gettype($cell)));
470 if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
471 $nbLines = $cell->getRowspan() - 1;
472 $lines = array($cell);
473 if (strstr($cell, "\n")) {
474 $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
475 $nbLines = \count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
477 $rows[$line][$column] = new TableCell($lines[0], array('colspan' => $cell->getColspan()));
481 // create a two dimensional array (rowspan x colspan)
482 $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, array()), $unmergedRows);
483 foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
484 $value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
485 $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, array('colspan' => $cell->getColspan()));
486 if ($nbLines === $unmergedRowKey - $line) {
493 foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
494 // we need to know if $unmergedRow will be merged or inserted into $rows
495 if (isset($rows[$unmergedRowKey]) && \is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
496 foreach ($unmergedRow as $cellKey => $cell) {
497 // insert cell into row at cellKey position
498 array_splice($rows[$unmergedRowKey], $cellKey, 0, array($cell));
501 $row = $this->copyRow($rows, $unmergedRowKey - 1);
502 foreach ($unmergedRow as $column => $cell) {
504 $row[$column] = $unmergedRow[$column];
507 array_splice($rows, $unmergedRowKey, 0, array($row));
515 * fill cells for a row that contains colspan > 1.
519 private function fillCells($row)
522 foreach ($row as $column => $cell) {
524 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
525 foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
526 // insert empty value at column position
532 return $newRow ?: $row;
541 private function copyRow(array $rows, $line)
544 foreach ($row as $cellKey => $cellValue) {
546 if ($cellValue instanceof TableCell) {
547 $row[$cellKey] = new TableCell('', array('colspan' => $cellValue->getColspan()));
555 * 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.
574 private function getRowColumns(array $row)
576 $columns = range(0, $this->numberOfColumns - 1);
577 foreach ($row as $cellKey => $cell) {
578 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
579 // exclude grouped columns.
580 $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
588 * Calculates columns widths.
590 private function calculateColumnsWidth(array $rows)
592 for ($column = 0; $column < $this->numberOfColumns; ++$column) {
594 foreach ($rows as $row) {
595 if ($row instanceof TableSeparator) {
599 foreach ($row as $i => $cell) {
600 if ($cell instanceof TableCell) {
601 $textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
602 $textLength = Helper::strlen($textContent);
603 if ($textLength > 0) {
604 $contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
605 foreach ($contentColumns as $position => $content) {
606 $row[$i + $position] = $content;
612 $lengths[] = $this->getCellWidth($row, $column);
615 $this->effectiveColumnWidths[$column] = max($lengths) + Helper::strlen($this->style->getCellRowContentFormat()) - 2;
624 private function getColumnSeparatorWidth()
626 return Helper::strlen(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
637 private function getCellWidth(array $row, $column)
641 if (isset($row[$column])) {
642 $cell = $row[$column];
643 $cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
646 $columnWidth = isset($this->columnWidths[$column]) ? $this->columnWidths[$column] : 0;
648 return max($cellWidth, $columnWidth);
652 * Called after rendering to cleanup cache data.
654 private function cleanup()
656 $this->effectiveColumnWidths = array();
657 $this->numberOfColumns = null;
660 private static function initStyles()
662 $borderless = new TableStyle();
664 ->setHorizontalBorderChar('=')
665 ->setVerticalBorderChar(' ')
666 ->setCrossingChar(' ')
669 $compact = new TableStyle();
671 ->setHorizontalBorderChar('')
672 ->setVerticalBorderChar(' ')
673 ->setCrossingChar('')
674 ->setCellRowContentFormat('%s')
677 $styleGuide = new TableStyle();
679 ->setHorizontalBorderChar('-')
680 ->setVerticalBorderChar(' ')
681 ->setCrossingChar(' ')
682 ->setCellHeaderFormat('%s')
686 'default' => new TableStyle(),
687 'borderless' => $borderless,
688 'compact' => $compact,
689 'symfony-style-guide' => $styleGuide,
693 private function resolveStyle($name)
695 if ($name instanceof TableStyle) {
699 if (isset(self::$styles[$name])) {
700 return self::$styles[$name];
703 throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));