Table.php 31 KB

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