Table.php 29 KB

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