PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Symfony/Component/Console/Helper/Table.php

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