Table.php 28 KB

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