Table.php 34 KB

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