暂无描述

Table.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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 = intval($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[intval($columnIndex)] = intval($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", $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", $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. }
  409. }
  410. }
  411. foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
  412. // we need to know if $unmergedRow will be merged or inserted into $rows
  413. if (isset($rows[$unmergedRowKey]) && is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
  414. foreach ($unmergedRow as $cellKey => $cell) {
  415. // insert cell into row at cellKey position
  416. array_splice($rows[$unmergedRowKey], $cellKey, 0, array($cell));
  417. }
  418. } else {
  419. $row = $this->copyRow($rows, $unmergedRowKey - 1);
  420. foreach ($unmergedRow as $column => $cell) {
  421. if (!empty($cell)) {
  422. $row[$column] = $unmergedRow[$column];
  423. }
  424. }
  425. array_splice($rows, $unmergedRowKey, 0, array($row));
  426. }
  427. }
  428. return $rows;
  429. }
  430. /**
  431. * fill cells for a row that contains colspan > 1.
  432. *
  433. * @param array $row
  434. *
  435. * @return array
  436. */
  437. private function fillCells($row)
  438. {
  439. $newRow = array();
  440. foreach ($row as $column => $cell) {
  441. $newRow[] = $cell;
  442. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  443. foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
  444. // insert empty value at column position
  445. $newRow[] = '';
  446. }
  447. }
  448. }
  449. return $newRow ?: $row;
  450. }
  451. /**
  452. * @param array $rows
  453. * @param int $line
  454. *
  455. * @return array
  456. */
  457. private function copyRow($rows, $line)
  458. {
  459. $row = $rows[$line];
  460. foreach ($row as $cellKey => $cellValue) {
  461. $row[$cellKey] = '';
  462. if ($cellValue instanceof TableCell) {
  463. $row[$cellKey] = new TableCell('', array('colspan' => $cellValue->getColspan()));
  464. }
  465. }
  466. return $row;
  467. }
  468. /**
  469. * Gets number of columns by row.
  470. *
  471. * @param array $row
  472. *
  473. * @return int
  474. */
  475. private function getNumberOfColumns(array $row)
  476. {
  477. $columns = count($row);
  478. foreach ($row as $column) {
  479. $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
  480. }
  481. return $columns;
  482. }
  483. /**
  484. * Gets list of columns for the given row.
  485. *
  486. * @param array $row
  487. *
  488. * @return array
  489. */
  490. private function getRowColumns($row)
  491. {
  492. $columns = range(0, $this->numberOfColumns - 1);
  493. foreach ($row as $cellKey => $cell) {
  494. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  495. // exclude grouped columns.
  496. $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
  497. }
  498. }
  499. return $columns;
  500. }
  501. /**
  502. * Calculates columns widths.
  503. *
  504. * @param array $rows
  505. */
  506. private function calculateColumnsWidth($rows)
  507. {
  508. for ($column = 0; $column < $this->numberOfColumns; ++$column) {
  509. $lengths = array();
  510. foreach ($rows as $row) {
  511. if ($row instanceof TableSeparator) {
  512. continue;
  513. }
  514. foreach ($row as $i => $cell) {
  515. if ($cell instanceof TableCell) {
  516. $textLength = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  517. if ($textLength > 0) {
  518. $contentColumns = str_split($cell, ceil($textLength / $cell->getColspan()));
  519. foreach ($contentColumns as $position => $content) {
  520. $row[$i + $position] = $content;
  521. }
  522. }
  523. }
  524. }
  525. $lengths[] = $this->getCellWidth($row, $column);
  526. }
  527. $this->effectiveColumnWidths[$column] = max($lengths) + strlen($this->style->getCellRowContentFormat()) - 2;
  528. }
  529. }
  530. /**
  531. * Gets column width.
  532. *
  533. * @return int
  534. */
  535. private function getColumnSeparatorWidth()
  536. {
  537. return strlen(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
  538. }
  539. /**
  540. * Gets cell width.
  541. *
  542. * @param array $row
  543. * @param int $column
  544. *
  545. * @return int
  546. */
  547. private function getCellWidth(array $row, $column)
  548. {
  549. $cellWidth = 0;
  550. if (isset($row[$column])) {
  551. $cell = $row[$column];
  552. $cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  553. }
  554. $columnWidth = isset($this->columnWidths[$column]) ? $this->columnWidths[$column] : 0;
  555. return max($cellWidth, $columnWidth);
  556. }
  557. /**
  558. * Called after rendering to cleanup cache data.
  559. */
  560. private function cleanup()
  561. {
  562. $this->effectiveColumnWidths = array();
  563. $this->numberOfColumns = null;
  564. }
  565. private static function initStyles()
  566. {
  567. $borderless = new TableStyle();
  568. $borderless
  569. ->setHorizontalBorderChar('=')
  570. ->setVerticalBorderChar(' ')
  571. ->setCrossingChar(' ')
  572. ;
  573. $compact = new TableStyle();
  574. $compact
  575. ->setHorizontalBorderChar('')
  576. ->setVerticalBorderChar(' ')
  577. ->setCrossingChar('')
  578. ->setCellRowContentFormat('%s')
  579. ;
  580. $styleGuide = new TableStyle();
  581. $styleGuide
  582. ->setHorizontalBorderChar('-')
  583. ->setVerticalBorderChar(' ')
  584. ->setCrossingChar(' ')
  585. ->setCellHeaderFormat('%s')
  586. ;
  587. return array(
  588. 'default' => new TableStyle(),
  589. 'borderless' => $borderless,
  590. 'compact' => $compact,
  591. 'symfony-style-guide' => $styleGuide,
  592. );
  593. }
  594. private function resolveStyle($name)
  595. {
  596. if ($name instanceof TableStyle) {
  597. return $name;
  598. }
  599. if (isset(self::$styles[$name])) {
  600. return self::$styles[$name];
  601. }
  602. throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
  603. }
  604. }