Table.php 18 KB

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