Table.php 18 KB

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