Table.php 28 KB

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