Table.php 18 KB

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