Table.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Helper;
  11. use Symfony\Component\Console\Exception\InvalidArgumentException;
  12. use Symfony\Component\Console\Output\OutputInterface;
  13. /**
  14. * Provides helpers to display a table.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. * @author Саша Стаменковић <umpirsky@gmail.com>
  18. * @author Abdellatif Ait boudad <a.aitboudad@gmail.com>
  19. * @author Max Grigorian <maxakawizard@gmail.com>
  20. */
  21. class Table
  22. {
  23. /**
  24. * Table headers.
  25. */
  26. private $headers = array();
  27. /**
  28. * Table rows.
  29. */
  30. private $rows = array();
  31. /**
  32. * Column widths cache.
  33. */
  34. private $effectiveColumnWidths = array();
  35. /**
  36. * Number of columns cache.
  37. *
  38. * @var int
  39. */
  40. private $numberOfColumns;
  41. /**
  42. * @var OutputInterface
  43. */
  44. private $output;
  45. /**
  46. * @var TableStyle
  47. */
  48. private $style;
  49. /**
  50. * @var array
  51. */
  52. private $columnStyles = array();
  53. /**
  54. * User set column widths.
  55. *
  56. * @var array
  57. */
  58. private $columnWidths = array();
  59. private static $styles;
  60. public function __construct(OutputInterface $output)
  61. {
  62. $this->output = $output;
  63. if (!self::$styles) {
  64. self::$styles = self::initStyles();
  65. }
  66. $this->setStyle('default');
  67. }
  68. /**
  69. * Sets a style definition.
  70. *
  71. * @param string $name The style name
  72. * @param TableStyle $style A TableStyle instance
  73. */
  74. public static function setStyleDefinition($name, TableStyle $style)
  75. {
  76. if (!self::$styles) {
  77. self::$styles = self::initStyles();
  78. }
  79. self::$styles[$name] = $style;
  80. }
  81. /**
  82. * Gets a style definition by name.
  83. *
  84. * @param string $name The style name
  85. *
  86. * @return TableStyle
  87. */
  88. public static function getStyleDefinition($name)
  89. {
  90. if (!self::$styles) {
  91. self::$styles = self::initStyles();
  92. }
  93. if (isset(self::$styles[$name])) {
  94. return self::$styles[$name];
  95. }
  96. throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
  97. }
  98. /**
  99. * Sets table style.
  100. *
  101. * @param TableStyle|string $name The style name or a TableStyle instance
  102. *
  103. * @return $this
  104. */
  105. public function setStyle($name)
  106. {
  107. $this->style = $this->resolveStyle($name);
  108. return $this;
  109. }
  110. /**
  111. * Gets the current table style.
  112. *
  113. * @return TableStyle
  114. */
  115. public function getStyle()
  116. {
  117. return $this->style;
  118. }
  119. /**
  120. * Sets table column style.
  121. *
  122. * @param int $columnIndex Column index
  123. * @param TableStyle|string $name The style name or a TableStyle instance
  124. *
  125. * @return $this
  126. */
  127. public function setColumnStyle($columnIndex, $name)
  128. {
  129. $columnIndex = (int) $columnIndex;
  130. $this->columnStyles[$columnIndex] = $this->resolveStyle($name);
  131. return $this;
  132. }
  133. /**
  134. * Gets the current style for a column.
  135. *
  136. * If style was not set, it returns the global table style.
  137. *
  138. * @param int $columnIndex Column index
  139. *
  140. * @return TableStyle
  141. */
  142. public function getColumnStyle($columnIndex)
  143. {
  144. if (isset($this->columnStyles[$columnIndex])) {
  145. return $this->columnStyles[$columnIndex];
  146. }
  147. return $this->getStyle();
  148. }
  149. /**
  150. * Sets the minimum width of a column.
  151. *
  152. * @param int $columnIndex Column index
  153. * @param int $width Minimum column width in characters
  154. *
  155. * @return $this
  156. */
  157. public function setColumnWidth($columnIndex, $width)
  158. {
  159. $this->columnWidths[(int) $columnIndex] = (int) $width;
  160. return $this;
  161. }
  162. /**
  163. * Sets the minimum width of all columns.
  164. *
  165. * @param array $widths
  166. *
  167. * @return $this
  168. */
  169. public function setColumnWidths(array $widths)
  170. {
  171. $this->columnWidths = array();
  172. foreach ($widths as $index => $width) {
  173. $this->setColumnWidth($index, $width);
  174. }
  175. return $this;
  176. }
  177. public function setHeaders(array $headers)
  178. {
  179. $headers = array_values($headers);
  180. if (!empty($headers) && !\is_array($headers[0])) {
  181. $headers = array($headers);
  182. }
  183. $this->headers = $headers;
  184. return $this;
  185. }
  186. public function setRows(array $rows)
  187. {
  188. $this->rows = array();
  189. return $this->addRows($rows);
  190. }
  191. public function addRows(array $rows)
  192. {
  193. foreach ($rows as $row) {
  194. $this->addRow($row);
  195. }
  196. return $this;
  197. }
  198. public function addRow($row)
  199. {
  200. if ($row instanceof TableSeparator) {
  201. $this->rows[] = $row;
  202. return $this;
  203. }
  204. if (!\is_array($row)) {
  205. throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.');
  206. }
  207. $this->rows[] = array_values($row);
  208. return $this;
  209. }
  210. public function setRow($column, array $row)
  211. {
  212. $this->rows[$column] = $row;
  213. return $this;
  214. }
  215. /**
  216. * Renders table to output.
  217. *
  218. * Example:
  219. * <code>
  220. * +---------------+-----------------------+------------------+
  221. * | ISBN | Title | Author |
  222. * +---------------+-----------------------+------------------+
  223. * | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
  224. * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
  225. * | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
  226. * +---------------+-----------------------+------------------+
  227. * </code>
  228. */
  229. public function render()
  230. {
  231. $this->calculateNumberOfColumns();
  232. $rows = $this->buildTableRows($this->rows);
  233. $headers = $this->buildTableRows($this->headers);
  234. $this->calculateColumnsWidth(array_merge($headers, $rows));
  235. $this->renderRowSeparator();
  236. if (!empty($headers)) {
  237. foreach ($headers as $header) {
  238. $this->renderRow($header, $this->style->getCellHeaderFormat());
  239. $this->renderRowSeparator();
  240. }
  241. }
  242. foreach ($rows as $row) {
  243. if ($row instanceof TableSeparator) {
  244. $this->renderRowSeparator();
  245. } else {
  246. $this->renderRow($row, $this->style->getCellRowFormat());
  247. }
  248. }
  249. if (!empty($rows)) {
  250. $this->renderRowSeparator();
  251. }
  252. $this->cleanup();
  253. }
  254. /**
  255. * Renders horizontal header separator.
  256. *
  257. * Example: <code>+-----+-----------+-------+</code>
  258. */
  259. private function renderRowSeparator()
  260. {
  261. if (0 === $count = $this->numberOfColumns) {
  262. return;
  263. }
  264. if (!$this->style->getHorizontalBorderChar() && !$this->style->getCrossingChar()) {
  265. return;
  266. }
  267. $markup = $this->style->getCrossingChar();
  268. for ($column = 0; $column < $count; ++$column) {
  269. $markup .= str_repeat($this->style->getHorizontalBorderChar(), $this->effectiveColumnWidths[$column]).$this->style->getCrossingChar();
  270. }
  271. $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
  272. }
  273. /**
  274. * Renders vertical column separator.
  275. */
  276. private function renderColumnSeparator()
  277. {
  278. return sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar());
  279. }
  280. /**
  281. * Renders table row.
  282. *
  283. * Example: <code>| 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |</code>
  284. *
  285. * @param array $row
  286. * @param string $cellFormat
  287. */
  288. private function renderRow(array $row, $cellFormat)
  289. {
  290. if (empty($row)) {
  291. return;
  292. }
  293. $rowContent = $this->renderColumnSeparator();
  294. foreach ($this->getRowColumns($row) as $column) {
  295. $rowContent .= $this->renderCell($row, $column, $cellFormat);
  296. $rowContent .= $this->renderColumnSeparator();
  297. }
  298. $this->output->writeln($rowContent);
  299. }
  300. /**
  301. * Renders table cell with padding.
  302. *
  303. * @param array $row
  304. * @param int $column
  305. * @param string $cellFormat
  306. */
  307. private function renderCell(array $row, $column, $cellFormat)
  308. {
  309. $cell = isset($row[$column]) ? $row[$column] : '';
  310. $width = $this->effectiveColumnWidths[$column];
  311. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  312. // add the width of the following columns(numbers of colspan).
  313. foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
  314. $width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn];
  315. }
  316. }
  317. // str_pad won't work properly with multi-byte strings, we need to fix the padding
  318. if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
  319. $width += \strlen($cell) - mb_strwidth($cell, $encoding);
  320. }
  321. $style = $this->getColumnStyle($column);
  322. if ($cell instanceof TableSeparator) {
  323. return sprintf($style->getBorderFormat(), str_repeat($style->getHorizontalBorderChar(), $width));
  324. }
  325. $width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  326. $content = sprintf($style->getCellRowContentFormat(), $cell);
  327. return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType()));
  328. }
  329. /**
  330. * Calculate number of columns for this table.
  331. */
  332. private function calculateNumberOfColumns()
  333. {
  334. if (null !== $this->numberOfColumns) {
  335. return;
  336. }
  337. $columns = array(0);
  338. foreach (array_merge($this->headers, $this->rows) as $row) {
  339. if ($row instanceof TableSeparator) {
  340. continue;
  341. }
  342. $columns[] = $this->getNumberOfColumns($row);
  343. }
  344. $this->numberOfColumns = max($columns);
  345. }
  346. private function buildTableRows($rows)
  347. {
  348. $unmergedRows = array();
  349. for ($rowKey = 0; $rowKey < \count($rows); ++$rowKey) {
  350. $rows = $this->fillNextRows($rows, $rowKey);
  351. // Remove any new line breaks and replace it with a new line
  352. foreach ($rows[$rowKey] as $column => $cell) {
  353. if (!strstr($cell, "\n")) {
  354. continue;
  355. }
  356. $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
  357. foreach ($lines as $lineKey => $line) {
  358. if ($cell instanceof TableCell) {
  359. $line = new TableCell($line, array('colspan' => $cell->getColspan()));
  360. }
  361. if (0 === $lineKey) {
  362. $rows[$rowKey][$column] = $line;
  363. } else {
  364. $unmergedRows[$rowKey][$lineKey][$column] = $line;
  365. }
  366. }
  367. }
  368. }
  369. $tableRows = array();
  370. foreach ($rows as $rowKey => $row) {
  371. $tableRows[] = $this->fillCells($row);
  372. if (isset($unmergedRows[$rowKey])) {
  373. $tableRows = array_merge($tableRows, $unmergedRows[$rowKey]);
  374. }
  375. }
  376. return $tableRows;
  377. }
  378. /**
  379. * fill rows that contains rowspan > 1.
  380. *
  381. * @param array $rows
  382. * @param int $line
  383. *
  384. * @return array
  385. *
  386. * @throws InvalidArgumentException
  387. */
  388. private function fillNextRows(array $rows, $line)
  389. {
  390. $unmergedRows = array();
  391. foreach ($rows[$line] as $column => $cell) {
  392. if (null !== $cell && !$cell instanceof TableCell && !is_scalar($cell) && !(\is_object($cell) && method_exists($cell, '__toString'))) {
  393. throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing __toString, %s given.', \gettype($cell)));
  394. }
  395. if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
  396. $nbLines = $cell->getRowspan() - 1;
  397. $lines = array($cell);
  398. if (strstr($cell, "\n")) {
  399. $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
  400. $nbLines = \count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
  401. $rows[$line][$column] = new TableCell($lines[0], array('colspan' => $cell->getColspan()));
  402. unset($lines[0]);
  403. }
  404. // create a two dimensional array (rowspan x colspan)
  405. $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, array()), $unmergedRows);
  406. foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
  407. $value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
  408. $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, array('colspan' => $cell->getColspan()));
  409. if ($nbLines === $unmergedRowKey - $line) {
  410. break;
  411. }
  412. }
  413. }
  414. }
  415. foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
  416. // we need to know if $unmergedRow will be merged or inserted into $rows
  417. if (isset($rows[$unmergedRowKey]) && \is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
  418. foreach ($unmergedRow as $cellKey => $cell) {
  419. // insert cell into row at cellKey position
  420. array_splice($rows[$unmergedRowKey], $cellKey, 0, array($cell));
  421. }
  422. } else {
  423. $row = $this->copyRow($rows, $unmergedRowKey - 1);
  424. foreach ($unmergedRow as $column => $cell) {
  425. if (!empty($cell)) {
  426. $row[$column] = $unmergedRow[$column];
  427. }
  428. }
  429. array_splice($rows, $unmergedRowKey, 0, array($row));
  430. }
  431. }
  432. return $rows;
  433. }
  434. /**
  435. * fill cells for a row that contains colspan > 1.
  436. *
  437. * @return array
  438. */
  439. private function fillCells($row)
  440. {
  441. $newRow = array();
  442. foreach ($row as $column => $cell) {
  443. $newRow[] = $cell;
  444. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  445. foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
  446. // insert empty value at column position
  447. $newRow[] = '';
  448. }
  449. }
  450. }
  451. return $newRow ?: $row;
  452. }
  453. /**
  454. * @param array $rows
  455. * @param int $line
  456. *
  457. * @return array
  458. */
  459. private function copyRow(array $rows, $line)
  460. {
  461. $row = $rows[$line];
  462. foreach ($row as $cellKey => $cellValue) {
  463. $row[$cellKey] = '';
  464. if ($cellValue instanceof TableCell) {
  465. $row[$cellKey] = new TableCell('', array('colspan' => $cellValue->getColspan()));
  466. }
  467. }
  468. return $row;
  469. }
  470. /**
  471. * Gets number of columns by row.
  472. *
  473. * @return int
  474. */
  475. private function getNumberOfColumns(array $row)
  476. {
  477. $columns = \count($row);
  478. foreach ($row as $column) {
  479. $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
  480. }
  481. return $columns;
  482. }
  483. /**
  484. * Gets list of columns for the given row.
  485. *
  486. * @return array
  487. */
  488. private function getRowColumns(array $row)
  489. {
  490. $columns = range(0, $this->numberOfColumns - 1);
  491. foreach ($row as $cellKey => $cell) {
  492. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  493. // exclude grouped columns.
  494. $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
  495. }
  496. }
  497. return $columns;
  498. }
  499. /**
  500. * Calculates columns widths.
  501. */
  502. private function calculateColumnsWidth(array $rows)
  503. {
  504. for ($column = 0; $column < $this->numberOfColumns; ++$column) {
  505. $lengths = array();
  506. foreach ($rows as $row) {
  507. if ($row instanceof TableSeparator) {
  508. continue;
  509. }
  510. foreach ($row as $i => $cell) {
  511. if ($cell instanceof TableCell) {
  512. $textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
  513. $textLength = Helper::strlen($textContent);
  514. if ($textLength > 0) {
  515. $contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
  516. foreach ($contentColumns as $position => $content) {
  517. $row[$i + $position] = $content;
  518. }
  519. }
  520. }
  521. }
  522. $lengths[] = $this->getCellWidth($row, $column);
  523. }
  524. $this->effectiveColumnWidths[$column] = max($lengths) + \strlen($this->style->getCellRowContentFormat()) - 2;
  525. }
  526. }
  527. /**
  528. * Gets column width.
  529. *
  530. * @return int
  531. */
  532. private function getColumnSeparatorWidth()
  533. {
  534. return \strlen(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
  535. }
  536. /**
  537. * Gets cell width.
  538. *
  539. * @param array $row
  540. * @param int $column
  541. *
  542. * @return int
  543. */
  544. private function getCellWidth(array $row, $column)
  545. {
  546. $cellWidth = 0;
  547. if (isset($row[$column])) {
  548. $cell = $row[$column];
  549. $cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  550. }
  551. $columnWidth = isset($this->columnWidths[$column]) ? $this->columnWidths[$column] : 0;
  552. return max($cellWidth, $columnWidth);
  553. }
  554. /**
  555. * Called after rendering to cleanup cache data.
  556. */
  557. private function cleanup()
  558. {
  559. $this->effectiveColumnWidths = array();
  560. $this->numberOfColumns = null;
  561. }
  562. private static function initStyles()
  563. {
  564. $borderless = new TableStyle();
  565. $borderless
  566. ->setHorizontalBorderChar('=')
  567. ->setVerticalBorderChar(' ')
  568. ->setCrossingChar(' ')
  569. ;
  570. $compact = new TableStyle();
  571. $compact
  572. ->setHorizontalBorderChar('')
  573. ->setVerticalBorderChar(' ')
  574. ->setCrossingChar('')
  575. ->setCellRowContentFormat('%s')
  576. ;
  577. $styleGuide = new TableStyle();
  578. $styleGuide
  579. ->setHorizontalBorderChar('-')
  580. ->setVerticalBorderChar(' ')
  581. ->setCrossingChar(' ')
  582. ->setCellHeaderFormat('%s')
  583. ;
  584. return array(
  585. 'default' => new TableStyle(),
  586. 'borderless' => $borderless,
  587. 'compact' => $compact,
  588. 'symfony-style-guide' => $styleGuide,
  589. );
  590. }
  591. private function resolveStyle($name)
  592. {
  593. if ($name instanceof TableStyle) {
  594. return $name;
  595. }
  596. if (isset(self::$styles[$name])) {
  597. return self::$styles[$name];
  598. }
  599. throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
  600. }
  601. }