Table.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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\Exception\RuntimeException;
  13. use Symfony\Component\Console\Formatter\OutputFormatter;
  14. use Symfony\Component\Console\Formatter\WrappableOutputFormatterInterface;
  15. use Symfony\Component\Console\Output\ConsoleSectionOutput;
  16. use Symfony\Component\Console\Output\OutputInterface;
  17. /**
  18. * Provides helpers to display a table.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. * @author Саша Стаменковић <umpirsky@gmail.com>
  22. * @author Abdellatif Ait boudad <a.aitboudad@gmail.com>
  23. * @author Max Grigorian <maxakawizard@gmail.com>
  24. * @author Dany Maillard <danymaillard93b@gmail.com>
  25. */
  26. class Table
  27. {
  28. private const SEPARATOR_TOP = 0;
  29. private const SEPARATOR_TOP_BOTTOM = 1;
  30. private const SEPARATOR_MID = 2;
  31. private const SEPARATOR_BOTTOM = 3;
  32. private const BORDER_OUTSIDE = 0;
  33. private const BORDER_INSIDE = 1;
  34. private $headerTitle;
  35. private $footerTitle;
  36. /**
  37. * Table headers.
  38. */
  39. private $headers = [];
  40. /**
  41. * Table rows.
  42. */
  43. private $rows = [];
  44. private $horizontal = false;
  45. /**
  46. * Column widths cache.
  47. */
  48. private $effectiveColumnWidths = [];
  49. /**
  50. * Number of columns cache.
  51. *
  52. * @var int
  53. */
  54. private $numberOfColumns;
  55. /**
  56. * @var OutputInterface
  57. */
  58. private $output;
  59. /**
  60. * @var TableStyle
  61. */
  62. private $style;
  63. /**
  64. * @var array
  65. */
  66. private $columnStyles = [];
  67. /**
  68. * User set column widths.
  69. *
  70. * @var array
  71. */
  72. private $columnWidths = [];
  73. private $columnMaxWidths = [];
  74. private static $styles;
  75. private $rendered = false;
  76. public function __construct(OutputInterface $output)
  77. {
  78. $this->output = $output;
  79. if (!self::$styles) {
  80. self::$styles = self::initStyles();
  81. }
  82. $this->setStyle('default');
  83. }
  84. /**
  85. * Sets a style definition.
  86. */
  87. public static function setStyleDefinition(string $name, TableStyle $style)
  88. {
  89. if (!self::$styles) {
  90. self::$styles = self::initStyles();
  91. }
  92. self::$styles[$name] = $style;
  93. }
  94. /**
  95. * Gets a style definition by name.
  96. *
  97. * @return TableStyle
  98. */
  99. public static function getStyleDefinition(string $name)
  100. {
  101. if (!self::$styles) {
  102. self::$styles = self::initStyles();
  103. }
  104. if (isset(self::$styles[$name])) {
  105. return self::$styles[$name];
  106. }
  107. throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
  108. }
  109. /**
  110. * Sets table style.
  111. *
  112. * @param TableStyle|string $name The style name or a TableStyle instance
  113. *
  114. * @return $this
  115. */
  116. public function setStyle($name)
  117. {
  118. $this->style = $this->resolveStyle($name);
  119. return $this;
  120. }
  121. /**
  122. * Gets the current table style.
  123. *
  124. * @return TableStyle
  125. */
  126. public function getStyle()
  127. {
  128. return $this->style;
  129. }
  130. /**
  131. * Sets table column style.
  132. *
  133. * @param TableStyle|string $name The style name or a TableStyle instance
  134. *
  135. * @return $this
  136. */
  137. public function setColumnStyle(int $columnIndex, $name)
  138. {
  139. $this->columnStyles[$columnIndex] = $this->resolveStyle($name);
  140. return $this;
  141. }
  142. /**
  143. * Gets the current style for a column.
  144. *
  145. * If style was not set, it returns the global table style.
  146. *
  147. * @return TableStyle
  148. */
  149. public function getColumnStyle(int $columnIndex)
  150. {
  151. return $this->columnStyles[$columnIndex] ?? $this->getStyle();
  152. }
  153. /**
  154. * Sets the minimum width of a column.
  155. *
  156. * @return $this
  157. */
  158. public function setColumnWidth(int $columnIndex, int $width)
  159. {
  160. $this->columnWidths[$columnIndex] = $width;
  161. return $this;
  162. }
  163. /**
  164. * Sets the minimum width of all columns.
  165. *
  166. * @return $this
  167. */
  168. public function setColumnWidths(array $widths)
  169. {
  170. $this->columnWidths = [];
  171. foreach ($widths as $index => $width) {
  172. $this->setColumnWidth($index, $width);
  173. }
  174. return $this;
  175. }
  176. /**
  177. * Sets the maximum width of a column.
  178. *
  179. * Any cell within this column which contents exceeds the specified width will be wrapped into multiple lines, while
  180. * formatted strings are preserved.
  181. *
  182. * @return $this
  183. */
  184. public function setColumnMaxWidth(int $columnIndex, int $width): self
  185. {
  186. if (!$this->output->getFormatter() instanceof WrappableOutputFormatterInterface) {
  187. throw new \LogicException(sprintf('Setting a maximum column width is only supported when using a "%s" formatter, got "%s".', WrappableOutputFormatterInterface::class, get_debug_type($this->output->getFormatter())));
  188. }
  189. $this->columnMaxWidths[$columnIndex] = $width;
  190. return $this;
  191. }
  192. public function setHeaders(array $headers)
  193. {
  194. $headers = array_values($headers);
  195. if (!empty($headers) && !\is_array($headers[0])) {
  196. $headers = [$headers];
  197. }
  198. $this->headers = $headers;
  199. return $this;
  200. }
  201. public function setRows(array $rows)
  202. {
  203. $this->rows = [];
  204. return $this->addRows($rows);
  205. }
  206. public function addRows(array $rows)
  207. {
  208. foreach ($rows as $row) {
  209. $this->addRow($row);
  210. }
  211. return $this;
  212. }
  213. public function addRow($row)
  214. {
  215. if ($row instanceof TableSeparator) {
  216. $this->rows[] = $row;
  217. return $this;
  218. }
  219. if (!\is_array($row)) {
  220. throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.');
  221. }
  222. $this->rows[] = array_values($row);
  223. return $this;
  224. }
  225. /**
  226. * Adds a row to the table, and re-renders the table.
  227. */
  228. public function appendRow($row): self
  229. {
  230. if (!$this->output instanceof ConsoleSectionOutput) {
  231. throw new RuntimeException(sprintf('Output should be an instance of "%s" when calling "%s".', ConsoleSectionOutput::class, __METHOD__));
  232. }
  233. if ($this->rendered) {
  234. $this->output->clear($this->calculateRowCount());
  235. }
  236. $this->addRow($row);
  237. $this->render();
  238. return $this;
  239. }
  240. public function setRow($column, array $row)
  241. {
  242. $this->rows[$column] = $row;
  243. return $this;
  244. }
  245. public function setHeaderTitle(?string $title): self
  246. {
  247. $this->headerTitle = $title;
  248. return $this;
  249. }
  250. public function setFooterTitle(?string $title): self
  251. {
  252. $this->footerTitle = $title;
  253. return $this;
  254. }
  255. public function setHorizontal(bool $horizontal = true): self
  256. {
  257. $this->horizontal = $horizontal;
  258. return $this;
  259. }
  260. /**
  261. * Renders table to output.
  262. *
  263. * Example:
  264. *
  265. * +---------------+-----------------------+------------------+
  266. * | ISBN | Title | Author |
  267. * +---------------+-----------------------+------------------+
  268. * | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
  269. * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
  270. * | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
  271. * +---------------+-----------------------+------------------+
  272. */
  273. public function render()
  274. {
  275. $divider = new TableSeparator();
  276. if ($this->horizontal) {
  277. $rows = [];
  278. foreach ($this->headers[0] ?? [] as $i => $header) {
  279. $rows[$i] = [$header];
  280. foreach ($this->rows as $row) {
  281. if ($row instanceof TableSeparator) {
  282. continue;
  283. }
  284. if (isset($row[$i])) {
  285. $rows[$i][] = $row[$i];
  286. } elseif ($rows[$i][0] instanceof TableCell && $rows[$i][0]->getColspan() >= 2) {
  287. // Noop, there is a "title"
  288. } else {
  289. $rows[$i][] = null;
  290. }
  291. }
  292. }
  293. } else {
  294. $rows = array_merge($this->headers, [$divider], $this->rows);
  295. }
  296. $this->calculateNumberOfColumns($rows);
  297. $rows = $this->buildTableRows($rows);
  298. $this->calculateColumnsWidth($rows);
  299. $isHeader = !$this->horizontal;
  300. $isFirstRow = $this->horizontal;
  301. foreach ($rows as $row) {
  302. if ($divider === $row) {
  303. $isHeader = false;
  304. $isFirstRow = true;
  305. continue;
  306. }
  307. if ($row instanceof TableSeparator) {
  308. $this->renderRowSeparator();
  309. continue;
  310. }
  311. if (!$row) {
  312. continue;
  313. }
  314. if ($isHeader || $isFirstRow) {
  315. if ($isFirstRow) {
  316. $this->renderRowSeparator(self::SEPARATOR_TOP_BOTTOM);
  317. $isFirstRow = false;
  318. } else {
  319. $this->renderRowSeparator(self::SEPARATOR_TOP, $this->headerTitle, $this->style->getHeaderTitleFormat());
  320. }
  321. }
  322. if ($this->horizontal) {
  323. $this->renderRow($row, $this->style->getCellRowFormat(), $this->style->getCellHeaderFormat());
  324. } else {
  325. $this->renderRow($row, $isHeader ? $this->style->getCellHeaderFormat() : $this->style->getCellRowFormat());
  326. }
  327. }
  328. $this->renderRowSeparator(self::SEPARATOR_BOTTOM, $this->footerTitle, $this->style->getFooterTitleFormat());
  329. $this->cleanup();
  330. $this->rendered = true;
  331. }
  332. /**
  333. * Renders horizontal header separator.
  334. *
  335. * Example:
  336. *
  337. * +-----+-----------+-------+
  338. */
  339. private function renderRowSeparator(int $type = self::SEPARATOR_MID, string $title = null, string $titleFormat = null)
  340. {
  341. if (0 === $count = $this->numberOfColumns) {
  342. return;
  343. }
  344. $borders = $this->style->getBorderChars();
  345. if (!$borders[0] && !$borders[2] && !$this->style->getCrossingChar()) {
  346. return;
  347. }
  348. $crossings = $this->style->getCrossingChars();
  349. if (self::SEPARATOR_MID === $type) {
  350. list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[2], $crossings[8], $crossings[0], $crossings[4]];
  351. } elseif (self::SEPARATOR_TOP === $type) {
  352. list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[0], $crossings[1], $crossings[2], $crossings[3]];
  353. } elseif (self::SEPARATOR_TOP_BOTTOM === $type) {
  354. list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[0], $crossings[9], $crossings[10], $crossings[11]];
  355. } else {
  356. list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[0], $crossings[7], $crossings[6], $crossings[5]];
  357. }
  358. $markup = $leftChar;
  359. for ($column = 0; $column < $count; ++$column) {
  360. $markup .= str_repeat($horizontal, $this->effectiveColumnWidths[$column]);
  361. $markup .= $column === $count - 1 ? $rightChar : $midChar;
  362. }
  363. if (null !== $title) {
  364. $titleLength = Helper::strlenWithoutDecoration($formatter = $this->output->getFormatter(), $formattedTitle = sprintf($titleFormat, $title));
  365. $markupLength = Helper::strlen($markup);
  366. if ($titleLength > $limit = $markupLength - 4) {
  367. $titleLength = $limit;
  368. $formatLength = Helper::strlenWithoutDecoration($formatter, sprintf($titleFormat, ''));
  369. $formattedTitle = sprintf($titleFormat, Helper::substr($title, 0, $limit - $formatLength - 3).'...');
  370. }
  371. $titleStart = ($markupLength - $titleLength) / 2;
  372. if (false === mb_detect_encoding($markup, null, true)) {
  373. $markup = substr_replace($markup, $formattedTitle, $titleStart, $titleLength);
  374. } else {
  375. $markup = mb_substr($markup, 0, $titleStart).$formattedTitle.mb_substr($markup, $titleStart + $titleLength);
  376. }
  377. }
  378. $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
  379. }
  380. /**
  381. * Renders vertical column separator.
  382. */
  383. private function renderColumnSeparator(int $type = self::BORDER_OUTSIDE): string
  384. {
  385. $borders = $this->style->getBorderChars();
  386. return sprintf($this->style->getBorderFormat(), self::BORDER_OUTSIDE === $type ? $borders[1] : $borders[3]);
  387. }
  388. /**
  389. * Renders table row.
  390. *
  391. * Example:
  392. *
  393. * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
  394. */
  395. private function renderRow(array $row, string $cellFormat, string $firstCellFormat = null)
  396. {
  397. $rowContent = $this->renderColumnSeparator(self::BORDER_OUTSIDE);
  398. $columns = $this->getRowColumns($row);
  399. $last = \count($columns) - 1;
  400. foreach ($columns as $i => $column) {
  401. if ($firstCellFormat && 0 === $i) {
  402. $rowContent .= $this->renderCell($row, $column, $firstCellFormat);
  403. } else {
  404. $rowContent .= $this->renderCell($row, $column, $cellFormat);
  405. }
  406. $rowContent .= $this->renderColumnSeparator($last === $i ? self::BORDER_OUTSIDE : self::BORDER_INSIDE);
  407. }
  408. $this->output->writeln($rowContent);
  409. }
  410. /**
  411. * Renders table cell with padding.
  412. */
  413. private function renderCell(array $row, int $column, string $cellFormat): string
  414. {
  415. $cell = isset($row[$column]) ? $row[$column] : '';
  416. $width = $this->effectiveColumnWidths[$column];
  417. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  418. // add the width of the following columns(numbers of colspan).
  419. foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
  420. $width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn];
  421. }
  422. }
  423. // str_pad won't work properly with multi-byte strings, we need to fix the padding
  424. if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
  425. $width += \strlen($cell) - mb_strwidth($cell, $encoding);
  426. }
  427. $style = $this->getColumnStyle($column);
  428. if ($cell instanceof TableSeparator) {
  429. return sprintf($style->getBorderFormat(), str_repeat($style->getBorderChars()[2], $width));
  430. }
  431. $width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  432. $content = sprintf($style->getCellRowContentFormat(), $cell);
  433. return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType()));
  434. }
  435. /**
  436. * Calculate number of columns for this table.
  437. */
  438. private function calculateNumberOfColumns(array $rows)
  439. {
  440. $columns = [0];
  441. foreach ($rows as $row) {
  442. if ($row instanceof TableSeparator) {
  443. continue;
  444. }
  445. $columns[] = $this->getNumberOfColumns($row);
  446. }
  447. $this->numberOfColumns = max($columns);
  448. }
  449. private function buildTableRows(array $rows): TableRows
  450. {
  451. /** @var WrappableOutputFormatterInterface $formatter */
  452. $formatter = $this->output->getFormatter();
  453. $unmergedRows = [];
  454. for ($rowKey = 0; $rowKey < \count($rows); ++$rowKey) {
  455. $rows = $this->fillNextRows($rows, $rowKey);
  456. // Remove any new line breaks and replace it with a new line
  457. foreach ($rows[$rowKey] as $column => $cell) {
  458. $colspan = $cell instanceof TableCell ? $cell->getColspan() : 1;
  459. if (isset($this->columnMaxWidths[$column]) && Helper::strlenWithoutDecoration($formatter, $cell) > $this->columnMaxWidths[$column]) {
  460. $cell = $formatter->formatAndWrap($cell, $this->columnMaxWidths[$column] * $colspan);
  461. }
  462. if (!strstr($cell, "\n")) {
  463. continue;
  464. }
  465. $escaped = implode("\n", array_map([OutputFormatter::class, 'escapeTrailingBackslash'], explode("\n", $cell)));
  466. $cell = $cell instanceof TableCell ? new TableCell($escaped, ['colspan' => $cell->getColspan()]) : $escaped;
  467. $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
  468. foreach ($lines as $lineKey => $line) {
  469. if ($colspan > 1) {
  470. $line = new TableCell($line, ['colspan' => $colspan]);
  471. }
  472. if (0 === $lineKey) {
  473. $rows[$rowKey][$column] = $line;
  474. } else {
  475. if (!\array_key_exists($rowKey, $unmergedRows) || !\array_key_exists($lineKey, $unmergedRows[$rowKey])) {
  476. $unmergedRows[$rowKey][$lineKey] = $this->copyRow($rows, $rowKey);
  477. }
  478. $unmergedRows[$rowKey][$lineKey][$column] = $line;
  479. }
  480. }
  481. }
  482. }
  483. return new TableRows(function () use ($rows, $unmergedRows): \Traversable {
  484. foreach ($rows as $rowKey => $row) {
  485. yield $this->fillCells($row);
  486. if (isset($unmergedRows[$rowKey])) {
  487. foreach ($unmergedRows[$rowKey] as $unmergedRow) {
  488. yield $this->fillCells($unmergedRow);
  489. }
  490. }
  491. }
  492. });
  493. }
  494. private function calculateRowCount(): int
  495. {
  496. $numberOfRows = \count(iterator_to_array($this->buildTableRows(array_merge($this->headers, [new TableSeparator()], $this->rows))));
  497. if ($this->headers) {
  498. ++$numberOfRows; // Add row for header separator
  499. }
  500. if (\count($this->rows) > 0) {
  501. ++$numberOfRows; // Add row for footer separator
  502. }
  503. return $numberOfRows;
  504. }
  505. /**
  506. * fill rows that contains rowspan > 1.
  507. *
  508. * @throws InvalidArgumentException
  509. */
  510. private function fillNextRows(array $rows, int $line): array
  511. {
  512. $unmergedRows = [];
  513. foreach ($rows[$line] as $column => $cell) {
  514. if (null !== $cell && !$cell instanceof TableCell && !is_scalar($cell) && !(\is_object($cell) && method_exists($cell, '__toString'))) {
  515. throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing "__toString()", "%s" given.', get_debug_type($cell)));
  516. }
  517. if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
  518. $nbLines = $cell->getRowspan() - 1;
  519. $lines = [$cell];
  520. if (strstr($cell, "\n")) {
  521. $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
  522. $nbLines = \count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
  523. $rows[$line][$column] = new TableCell($lines[0], ['colspan' => $cell->getColspan()]);
  524. unset($lines[0]);
  525. }
  526. // create a two dimensional array (rowspan x colspan)
  527. $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, []), $unmergedRows);
  528. foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
  529. $value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
  530. $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, ['colspan' => $cell->getColspan()]);
  531. if ($nbLines === $unmergedRowKey - $line) {
  532. break;
  533. }
  534. }
  535. }
  536. }
  537. foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
  538. // we need to know if $unmergedRow will be merged or inserted into $rows
  539. if (isset($rows[$unmergedRowKey]) && \is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
  540. foreach ($unmergedRow as $cellKey => $cell) {
  541. // insert cell into row at cellKey position
  542. array_splice($rows[$unmergedRowKey], $cellKey, 0, [$cell]);
  543. }
  544. } else {
  545. $row = $this->copyRow($rows, $unmergedRowKey - 1);
  546. foreach ($unmergedRow as $column => $cell) {
  547. if (!empty($cell)) {
  548. $row[$column] = $unmergedRow[$column];
  549. }
  550. }
  551. array_splice($rows, $unmergedRowKey, 0, [$row]);
  552. }
  553. }
  554. return $rows;
  555. }
  556. /**
  557. * fill cells for a row that contains colspan > 1.
  558. */
  559. private function fillCells($row)
  560. {
  561. $newRow = [];
  562. foreach ($row as $column => $cell) {
  563. $newRow[] = $cell;
  564. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  565. foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
  566. // insert empty value at column position
  567. $newRow[] = '';
  568. }
  569. }
  570. }
  571. return $newRow ?: $row;
  572. }
  573. private function copyRow(array $rows, int $line): array
  574. {
  575. $row = $rows[$line];
  576. foreach ($row as $cellKey => $cellValue) {
  577. $row[$cellKey] = '';
  578. if ($cellValue instanceof TableCell) {
  579. $row[$cellKey] = new TableCell('', ['colspan' => $cellValue->getColspan()]);
  580. }
  581. }
  582. return $row;
  583. }
  584. /**
  585. * Gets number of columns by row.
  586. */
  587. private function getNumberOfColumns(array $row): int
  588. {
  589. $columns = \count($row);
  590. foreach ($row as $column) {
  591. $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
  592. }
  593. return $columns;
  594. }
  595. /**
  596. * Gets list of columns for the given row.
  597. */
  598. private function getRowColumns(array $row): array
  599. {
  600. $columns = range(0, $this->numberOfColumns - 1);
  601. foreach ($row as $cellKey => $cell) {
  602. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  603. // exclude grouped columns.
  604. $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
  605. }
  606. }
  607. return $columns;
  608. }
  609. /**
  610. * Calculates columns widths.
  611. */
  612. private function calculateColumnsWidth(iterable $rows)
  613. {
  614. for ($column = 0; $column < $this->numberOfColumns; ++$column) {
  615. $lengths = [];
  616. foreach ($rows as $row) {
  617. if ($row instanceof TableSeparator) {
  618. continue;
  619. }
  620. foreach ($row as $i => $cell) {
  621. if ($cell instanceof TableCell) {
  622. $textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
  623. $textLength = Helper::strlen($textContent);
  624. if ($textLength > 0) {
  625. $contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
  626. foreach ($contentColumns as $position => $content) {
  627. $row[$i + $position] = $content;
  628. }
  629. }
  630. }
  631. }
  632. $lengths[] = $this->getCellWidth($row, $column);
  633. }
  634. $this->effectiveColumnWidths[$column] = max($lengths) + Helper::strlen($this->style->getCellRowContentFormat()) - 2;
  635. }
  636. }
  637. private function getColumnSeparatorWidth(): int
  638. {
  639. return Helper::strlen(sprintf($this->style->getBorderFormat(), $this->style->getBorderChars()[3]));
  640. }
  641. private function getCellWidth(array $row, int $column): int
  642. {
  643. $cellWidth = 0;
  644. if (isset($row[$column])) {
  645. $cell = $row[$column];
  646. $cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  647. }
  648. $columnWidth = isset($this->columnWidths[$column]) ? $this->columnWidths[$column] : 0;
  649. $cellWidth = max($cellWidth, $columnWidth);
  650. return isset($this->columnMaxWidths[$column]) ? min($this->columnMaxWidths[$column], $cellWidth) : $cellWidth;
  651. }
  652. /**
  653. * Called after rendering to cleanup cache data.
  654. */
  655. private function cleanup()
  656. {
  657. $this->effectiveColumnWidths = [];
  658. $this->numberOfColumns = null;
  659. }
  660. private static function initStyles(): array
  661. {
  662. $borderless = new TableStyle();
  663. $borderless
  664. ->setHorizontalBorderChars('=')
  665. ->setVerticalBorderChars(' ')
  666. ->setDefaultCrossingChar(' ')
  667. ;
  668. $compact = new TableStyle();
  669. $compact
  670. ->setHorizontalBorderChars('')
  671. ->setVerticalBorderChars(' ')
  672. ->setDefaultCrossingChar('')
  673. ->setCellRowContentFormat('%s')
  674. ;
  675. $styleGuide = new TableStyle();
  676. $styleGuide
  677. ->setHorizontalBorderChars('-')
  678. ->setVerticalBorderChars(' ')
  679. ->setDefaultCrossingChar(' ')
  680. ->setCellHeaderFormat('%s')
  681. ;
  682. $box = (new TableStyle())
  683. ->setHorizontalBorderChars('─')
  684. ->setVerticalBorderChars('│')
  685. ->setCrossingChars('┼', '┌', '┬', '┐', '┤', '┘', '┴', '└', '├')
  686. ;
  687. $boxDouble = (new TableStyle())
  688. ->setHorizontalBorderChars('═', '─')
  689. ->setVerticalBorderChars('║', '│')
  690. ->setCrossingChars('┼', '╔', '╤', '╗', '╢', '╝', '╧', '╚', '╟', '╠', '╪', '╣')
  691. ;
  692. return [
  693. 'default' => new TableStyle(),
  694. 'borderless' => $borderless,
  695. 'compact' => $compact,
  696. 'symfony-style-guide' => $styleGuide,
  697. 'box' => $box,
  698. 'box-double' => $boxDouble,
  699. ];
  700. }
  701. private function resolveStyle($name): TableStyle
  702. {
  703. if ($name instanceof TableStyle) {
  704. return $name;
  705. }
  706. if (isset(self::$styles[$name])) {
  707. return self::$styles[$name];
  708. }
  709. throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
  710. }
  711. }