Table.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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 = [];
  27. /**
  28. * Table rows.
  29. */
  30. private $rows = [];
  31. /**
  32. * Column widths cache.
  33. */
  34. private $effectiveColumnWidths = [];
  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 = [];
  53. /**
  54. * User set column widths.
  55. *
  56. * @var array
  57. */
  58. private $columnWidths = [];
  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. * @return $this
  166. */
  167. public function setColumnWidths(array $widths)
  168. {
  169. $this->columnWidths = [];
  170. foreach ($widths as $index => $width) {
  171. $this->setColumnWidth($index, $width);
  172. }
  173. return $this;
  174. }
  175. public function setHeaders(array $headers)
  176. {
  177. $headers = array_values($headers);
  178. if (!empty($headers) && !\is_array($headers[0])) {
  179. $headers = [$headers];
  180. }
  181. $this->headers = $headers;
  182. return $this;
  183. }
  184. public function setRows(array $rows)
  185. {
  186. $this->rows = [];
  187. return $this->addRows($rows);
  188. }
  189. public function addRows(array $rows)
  190. {
  191. foreach ($rows as $row) {
  192. $this->addRow($row);
  193. }
  194. return $this;
  195. }
  196. public function addRow($row)
  197. {
  198. if ($row instanceof TableSeparator) {
  199. $this->rows[] = $row;
  200. return $this;
  201. }
  202. if (!\is_array($row)) {
  203. throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.');
  204. }
  205. $this->rows[] = array_values($row);
  206. return $this;
  207. }
  208. public function setRow($column, array $row)
  209. {
  210. $this->rows[$column] = $row;
  211. return $this;
  212. }
  213. /**
  214. * Renders table to output.
  215. *
  216. * Example:
  217. *
  218. * +---------------+-----------------------+------------------+
  219. * | ISBN | Title | Author |
  220. * +---------------+-----------------------+------------------+
  221. * | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
  222. * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
  223. * | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
  224. * +---------------+-----------------------+------------------+
  225. */
  226. public function render()
  227. {
  228. $this->calculateNumberOfColumns();
  229. $rows = $this->buildTableRows($this->rows);
  230. $headers = $this->buildTableRows($this->headers);
  231. $this->calculateColumnsWidth(array_merge($headers, $rows));
  232. $this->renderRowSeparator();
  233. if (!empty($headers)) {
  234. foreach ($headers as $header) {
  235. $this->renderRow($header, $this->style->getCellHeaderFormat());
  236. $this->renderRowSeparator();
  237. }
  238. }
  239. foreach ($rows as $row) {
  240. if ($row instanceof TableSeparator) {
  241. $this->renderRowSeparator();
  242. } else {
  243. $this->renderRow($row, $this->style->getCellRowFormat());
  244. }
  245. }
  246. if (!empty($rows)) {
  247. $this->renderRowSeparator();
  248. }
  249. $this->cleanup();
  250. }
  251. /**
  252. * Renders horizontal header separator.
  253. *
  254. * Example:
  255. *
  256. * +-----+-----------+-------+
  257. */
  258. private function renderRowSeparator()
  259. {
  260. if (0 === $count = $this->numberOfColumns) {
  261. return;
  262. }
  263. if (!$this->style->getHorizontalBorderChar() && !$this->style->getCrossingChar()) {
  264. return;
  265. }
  266. $markup = $this->style->getCrossingChar();
  267. for ($column = 0; $column < $count; ++$column) {
  268. $markup .= str_repeat($this->style->getHorizontalBorderChar(), $this->effectiveColumnWidths[$column]).$this->style->getCrossingChar();
  269. }
  270. $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
  271. }
  272. /**
  273. * Renders vertical column separator.
  274. */
  275. private function renderColumnSeparator()
  276. {
  277. return sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar());
  278. }
  279. /**
  280. * Renders table row.
  281. *
  282. * Example:
  283. *
  284. * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
  285. *
  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 int $column
  304. * @param string $cellFormat
  305. */
  306. private function renderCell(array $row, $column, $cellFormat)
  307. {
  308. $cell = isset($row[$column]) ? $row[$column] : '';
  309. $width = $this->effectiveColumnWidths[$column];
  310. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  311. // add the width of the following columns(numbers of colspan).
  312. foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
  313. $width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn];
  314. }
  315. }
  316. // str_pad won't work properly with multi-byte strings, we need to fix the padding
  317. if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
  318. $width += \strlen($cell) - mb_strwidth($cell, $encoding);
  319. }
  320. $style = $this->getColumnStyle($column);
  321. if ($cell instanceof TableSeparator) {
  322. return sprintf($style->getBorderFormat(), str_repeat($style->getHorizontalBorderChar(), $width));
  323. }
  324. $width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  325. $content = sprintf($style->getCellRowContentFormat(), $cell);
  326. return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType()));
  327. }
  328. /**
  329. * Calculate number of columns for this table.
  330. */
  331. private function calculateNumberOfColumns()
  332. {
  333. if (null !== $this->numberOfColumns) {
  334. return;
  335. }
  336. $columns = [0];
  337. foreach (array_merge($this->headers, $this->rows) as $row) {
  338. if ($row instanceof TableSeparator) {
  339. continue;
  340. }
  341. $columns[] = $this->getNumberOfColumns($row);
  342. }
  343. $this->numberOfColumns = max($columns);
  344. }
  345. private function buildTableRows($rows)
  346. {
  347. $unmergedRows = [];
  348. for ($rowKey = 0; $rowKey < \count($rows); ++$rowKey) {
  349. $rows = $this->fillNextRows($rows, $rowKey);
  350. // Remove any new line breaks and replace it with a new line
  351. foreach ($rows[$rowKey] as $column => $cell) {
  352. if (!strstr($cell, "\n")) {
  353. continue;
  354. }
  355. $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
  356. foreach ($lines as $lineKey => $line) {
  357. if ($cell instanceof TableCell) {
  358. $line = new TableCell($line, ['colspan' => $cell->getColspan()]);
  359. }
  360. if (0 === $lineKey) {
  361. $rows[$rowKey][$column] = $line;
  362. } else {
  363. $unmergedRows[$rowKey][$lineKey][$column] = $line;
  364. }
  365. }
  366. }
  367. }
  368. $tableRows = [];
  369. foreach ($rows as $rowKey => $row) {
  370. $tableRows[] = $this->fillCells($row);
  371. if (isset($unmergedRows[$rowKey])) {
  372. $tableRows = array_merge($tableRows, $unmergedRows[$rowKey]);
  373. }
  374. }
  375. return $tableRows;
  376. }
  377. /**
  378. * fill rows that contains rowspan > 1.
  379. *
  380. * @param int $line
  381. *
  382. * @return array
  383. *
  384. * @throws InvalidArgumentException
  385. */
  386. private function fillNextRows(array $rows, $line)
  387. {
  388. $unmergedRows = [];
  389. foreach ($rows[$line] as $column => $cell) {
  390. if (null !== $cell && !$cell instanceof TableCell && !is_scalar($cell) && !(\is_object($cell) && method_exists($cell, '__toString'))) {
  391. throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing __toString, %s given.', \gettype($cell)));
  392. }
  393. if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
  394. $nbLines = $cell->getRowspan() - 1;
  395. $lines = [$cell];
  396. if (strstr($cell, "\n")) {
  397. $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
  398. $nbLines = \count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
  399. $rows[$line][$column] = new TableCell($lines[0], ['colspan' => $cell->getColspan()]);
  400. unset($lines[0]);
  401. }
  402. // create a two dimensional array (rowspan x colspan)
  403. $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, []), $unmergedRows);
  404. foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
  405. $value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
  406. $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, ['colspan' => $cell->getColspan()]);
  407. if ($nbLines === $unmergedRowKey - $line) {
  408. break;
  409. }
  410. }
  411. }
  412. }
  413. foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
  414. // we need to know if $unmergedRow will be merged or inserted into $rows
  415. if (isset($rows[$unmergedRowKey]) && \is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
  416. foreach ($unmergedRow as $cellKey => $cell) {
  417. // insert cell into row at cellKey position
  418. array_splice($rows[$unmergedRowKey], $cellKey, 0, [$cell]);
  419. }
  420. } else {
  421. $row = $this->copyRow($rows, $unmergedRowKey - 1);
  422. foreach ($unmergedRow as $column => $cell) {
  423. if (!empty($cell)) {
  424. $row[$column] = $unmergedRow[$column];
  425. }
  426. }
  427. array_splice($rows, $unmergedRowKey, 0, [$row]);
  428. }
  429. }
  430. return $rows;
  431. }
  432. /**
  433. * fill cells for a row that contains colspan > 1.
  434. *
  435. * @return array
  436. */
  437. private function fillCells($row)
  438. {
  439. $newRow = [];
  440. foreach ($row as $column => $cell) {
  441. $newRow[] = $cell;
  442. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  443. foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
  444. // insert empty value at column position
  445. $newRow[] = '';
  446. }
  447. }
  448. }
  449. return $newRow ?: $row;
  450. }
  451. /**
  452. * @param int $line
  453. *
  454. * @return array
  455. */
  456. private function copyRow(array $rows, $line)
  457. {
  458. $row = $rows[$line];
  459. foreach ($row as $cellKey => $cellValue) {
  460. $row[$cellKey] = '';
  461. if ($cellValue instanceof TableCell) {
  462. $row[$cellKey] = new TableCell('', ['colspan' => $cellValue->getColspan()]);
  463. }
  464. }
  465. return $row;
  466. }
  467. /**
  468. * Gets number of columns by row.
  469. *
  470. * @return int
  471. */
  472. private function getNumberOfColumns(array $row)
  473. {
  474. $columns = \count($row);
  475. foreach ($row as $column) {
  476. $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
  477. }
  478. return $columns;
  479. }
  480. /**
  481. * Gets list of columns for the given row.
  482. *
  483. * @return array
  484. */
  485. private function getRowColumns(array $row)
  486. {
  487. $columns = range(0, $this->numberOfColumns - 1);
  488. foreach ($row as $cellKey => $cell) {
  489. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  490. // exclude grouped columns.
  491. $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
  492. }
  493. }
  494. return $columns;
  495. }
  496. /**
  497. * Calculates columns widths.
  498. */
  499. private function calculateColumnsWidth(array $rows)
  500. {
  501. for ($column = 0; $column < $this->numberOfColumns; ++$column) {
  502. $lengths = [];
  503. foreach ($rows as $row) {
  504. if ($row instanceof TableSeparator) {
  505. continue;
  506. }
  507. foreach ($row as $i => $cell) {
  508. if ($cell instanceof TableCell) {
  509. $textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
  510. $textLength = Helper::strlen($textContent);
  511. if ($textLength > 0) {
  512. $contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
  513. foreach ($contentColumns as $position => $content) {
  514. $row[$i + $position] = $content;
  515. }
  516. }
  517. }
  518. }
  519. $lengths[] = $this->getCellWidth($row, $column);
  520. }
  521. $this->effectiveColumnWidths[$column] = max($lengths) + Helper::strlen($this->style->getCellRowContentFormat()) - 2;
  522. }
  523. }
  524. /**
  525. * Gets column width.
  526. *
  527. * @return int
  528. */
  529. private function getColumnSeparatorWidth()
  530. {
  531. return Helper::strlen(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
  532. }
  533. /**
  534. * Gets cell width.
  535. *
  536. * @param int $column
  537. *
  538. * @return int
  539. */
  540. private function getCellWidth(array $row, $column)
  541. {
  542. $cellWidth = 0;
  543. if (isset($row[$column])) {
  544. $cell = $row[$column];
  545. $cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  546. }
  547. $columnWidth = isset($this->columnWidths[$column]) ? $this->columnWidths[$column] : 0;
  548. return max($cellWidth, $columnWidth);
  549. }
  550. /**
  551. * Called after rendering to cleanup cache data.
  552. */
  553. private function cleanup()
  554. {
  555. $this->effectiveColumnWidths = [];
  556. $this->numberOfColumns = null;
  557. }
  558. private static function initStyles()
  559. {
  560. $borderless = new TableStyle();
  561. $borderless
  562. ->setHorizontalBorderChar('=')
  563. ->setVerticalBorderChar(' ')
  564. ->setCrossingChar(' ')
  565. ;
  566. $compact = new TableStyle();
  567. $compact
  568. ->setHorizontalBorderChar('')
  569. ->setVerticalBorderChar(' ')
  570. ->setCrossingChar('')
  571. ->setCellRowContentFormat('%s')
  572. ;
  573. $styleGuide = new TableStyle();
  574. $styleGuide
  575. ->setHorizontalBorderChar('-')
  576. ->setVerticalBorderChar(' ')
  577. ->setCrossingChar(' ')
  578. ->setCellHeaderFormat('%s')
  579. ;
  580. return [
  581. 'default' => new TableStyle(),
  582. 'borderless' => $borderless,
  583. 'compact' => $compact,
  584. 'symfony-style-guide' => $styleGuide,
  585. ];
  586. }
  587. private function resolveStyle($name)
  588. {
  589. if ($name instanceof TableStyle) {
  590. return $name;
  591. }
  592. if (isset(self::$styles[$name])) {
  593. return self::$styles[$name];
  594. }
  595. throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
  596. }
  597. }