Table.php 20 KB

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