Table.php 17 KB

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