Table.php 28 KB

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