菜谱项目

Table.php 19KB

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