Table.php 19 KB

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