Ei kuvausta

Table.php 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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. $rows = $this->buildTableRows($rows);
  309. $this->calculateColumnsWidth($rows);
  310. $isHeader = !$this->horizontal;
  311. $isFirstRow = $this->horizontal;
  312. $hasTitle = (bool) $this->headerTitle;
  313. foreach ($rows as $row) {
  314. if ($divider === $row) {
  315. $isHeader = false;
  316. $isFirstRow = true;
  317. continue;
  318. }
  319. if ($row instanceof TableSeparator) {
  320. $this->renderRowSeparator();
  321. continue;
  322. }
  323. if (!$row) {
  324. continue;
  325. }
  326. if ($isHeader || $isFirstRow) {
  327. $this->renderRowSeparator(
  328. $isHeader ? self::SEPARATOR_TOP : self::SEPARATOR_TOP_BOTTOM,
  329. $hasTitle ? $this->headerTitle : null,
  330. $hasTitle ? $this->style->getHeaderTitleFormat() : null
  331. );
  332. $isFirstRow = false;
  333. $hasTitle = false;
  334. }
  335. if ($this->horizontal) {
  336. $this->renderRow($row, $this->style->getCellRowFormat(), $this->style->getCellHeaderFormat());
  337. } else {
  338. $this->renderRow($row, $isHeader ? $this->style->getCellHeaderFormat() : $this->style->getCellRowFormat());
  339. }
  340. }
  341. $this->renderRowSeparator(self::SEPARATOR_BOTTOM, $this->footerTitle, $this->style->getFooterTitleFormat());
  342. $this->cleanup();
  343. $this->rendered = true;
  344. }
  345. /**
  346. * Renders horizontal header separator.
  347. *
  348. * Example:
  349. *
  350. * +-----+-----------+-------+
  351. */
  352. private function renderRowSeparator(int $type = self::SEPARATOR_MID, string $title = null, string $titleFormat = null)
  353. {
  354. if (0 === $count = $this->numberOfColumns) {
  355. return;
  356. }
  357. $borders = $this->style->getBorderChars();
  358. if (!$borders[0] && !$borders[2] && !$this->style->getCrossingChar()) {
  359. return;
  360. }
  361. $crossings = $this->style->getCrossingChars();
  362. if (self::SEPARATOR_MID === $type) {
  363. [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[2], $crossings[8], $crossings[0], $crossings[4]];
  364. } elseif (self::SEPARATOR_TOP === $type) {
  365. [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[1], $crossings[2], $crossings[3]];
  366. } elseif (self::SEPARATOR_TOP_BOTTOM === $type) {
  367. [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[9], $crossings[10], $crossings[11]];
  368. } else {
  369. [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[7], $crossings[6], $crossings[5]];
  370. }
  371. $markup = $leftChar;
  372. for ($column = 0; $column < $count; ++$column) {
  373. $markup .= str_repeat($horizontal, $this->effectiveColumnWidths[$column]);
  374. $markup .= $column === $count - 1 ? $rightChar : $midChar;
  375. }
  376. if (null !== $title) {
  377. $titleLength = Helper::strlenWithoutDecoration($formatter = $this->output->getFormatter(), $formattedTitle = sprintf($titleFormat, $title));
  378. $markupLength = Helper::strlen($markup);
  379. if ($titleLength > $limit = $markupLength - 4) {
  380. $titleLength = $limit;
  381. $formatLength = Helper::strlenWithoutDecoration($formatter, sprintf($titleFormat, ''));
  382. $formattedTitle = sprintf($titleFormat, Helper::substr($title, 0, $limit - $formatLength - 3).'...');
  383. }
  384. $titleStart = intdiv($markupLength - $titleLength, 2);
  385. if (false === mb_detect_encoding($markup, null, true)) {
  386. $markup = substr_replace($markup, $formattedTitle, $titleStart, $titleLength);
  387. } else {
  388. $markup = mb_substr($markup, 0, $titleStart).$formattedTitle.mb_substr($markup, $titleStart + $titleLength);
  389. }
  390. }
  391. $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
  392. }
  393. /**
  394. * Renders vertical column separator.
  395. */
  396. private function renderColumnSeparator(int $type = self::BORDER_OUTSIDE): string
  397. {
  398. $borders = $this->style->getBorderChars();
  399. return sprintf($this->style->getBorderFormat(), self::BORDER_OUTSIDE === $type ? $borders[1] : $borders[3]);
  400. }
  401. /**
  402. * Renders table row.
  403. *
  404. * Example:
  405. *
  406. * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
  407. */
  408. private function renderRow(array $row, string $cellFormat, string $firstCellFormat = null)
  409. {
  410. $rowContent = $this->renderColumnSeparator(self::BORDER_OUTSIDE);
  411. $columns = $this->getRowColumns($row);
  412. $last = \count($columns) - 1;
  413. foreach ($columns as $i => $column) {
  414. if ($firstCellFormat && 0 === $i) {
  415. $rowContent .= $this->renderCell($row, $column, $firstCellFormat);
  416. } else {
  417. $rowContent .= $this->renderCell($row, $column, $cellFormat);
  418. }
  419. $rowContent .= $this->renderColumnSeparator($last === $i ? self::BORDER_OUTSIDE : self::BORDER_INSIDE);
  420. }
  421. $this->output->writeln($rowContent);
  422. }
  423. /**
  424. * Renders table cell with padding.
  425. */
  426. private function renderCell(array $row, int $column, string $cellFormat): string
  427. {
  428. $cell = $row[$column] ?? '';
  429. $width = $this->effectiveColumnWidths[$column];
  430. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  431. // add the width of the following columns(numbers of colspan).
  432. foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
  433. $width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn];
  434. }
  435. }
  436. // str_pad won't work properly with multi-byte strings, we need to fix the padding
  437. if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
  438. $width += \strlen($cell) - mb_strwidth($cell, $encoding);
  439. }
  440. $style = $this->getColumnStyle($column);
  441. if ($cell instanceof TableSeparator) {
  442. return sprintf($style->getBorderFormat(), str_repeat($style->getBorderChars()[2], $width));
  443. }
  444. $width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  445. $content = sprintf($style->getCellRowContentFormat(), $cell);
  446. return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType()));
  447. }
  448. /**
  449. * Calculate number of columns for this table.
  450. */
  451. private function calculateNumberOfColumns(array $rows)
  452. {
  453. $columns = [0];
  454. foreach ($rows as $row) {
  455. if ($row instanceof TableSeparator) {
  456. continue;
  457. }
  458. $columns[] = $this->getNumberOfColumns($row);
  459. }
  460. $this->numberOfColumns = max($columns);
  461. }
  462. private function buildTableRows(array $rows): TableRows
  463. {
  464. /** @var WrappableOutputFormatterInterface $formatter */
  465. $formatter = $this->output->getFormatter();
  466. $unmergedRows = [];
  467. for ($rowKey = 0; $rowKey < \count($rows); ++$rowKey) {
  468. $rows = $this->fillNextRows($rows, $rowKey);
  469. // Remove any new line breaks and replace it with a new line
  470. foreach ($rows[$rowKey] as $column => $cell) {
  471. $colspan = $cell instanceof TableCell ? $cell->getColspan() : 1;
  472. if (isset($this->columnMaxWidths[$column]) && Helper::strlenWithoutDecoration($formatter, $cell) > $this->columnMaxWidths[$column]) {
  473. $cell = $formatter->formatAndWrap($cell, $this->columnMaxWidths[$column] * $colspan);
  474. }
  475. if (!strstr($cell ?? '', "\n")) {
  476. continue;
  477. }
  478. $escaped = implode("\n", array_map([OutputFormatter::class, 'escapeTrailingBackslash'], explode("\n", $cell)));
  479. $cell = $cell instanceof TableCell ? new TableCell($escaped, ['colspan' => $cell->getColspan()]) : $escaped;
  480. $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
  481. foreach ($lines as $lineKey => $line) {
  482. if ($colspan > 1) {
  483. $line = new TableCell($line, ['colspan' => $colspan]);
  484. }
  485. if (0 === $lineKey) {
  486. $rows[$rowKey][$column] = $line;
  487. } else {
  488. if (!\array_key_exists($rowKey, $unmergedRows) || !\array_key_exists($lineKey, $unmergedRows[$rowKey])) {
  489. $unmergedRows[$rowKey][$lineKey] = $this->copyRow($rows, $rowKey);
  490. }
  491. $unmergedRows[$rowKey][$lineKey][$column] = $line;
  492. }
  493. }
  494. }
  495. }
  496. return new TableRows(function () use ($rows, $unmergedRows): \Traversable {
  497. foreach ($rows as $rowKey => $row) {
  498. yield $row instanceof TableSeparator ? $row : $this->fillCells($row);
  499. if (isset($unmergedRows[$rowKey])) {
  500. foreach ($unmergedRows[$rowKey] as $row) {
  501. yield $row instanceof TableSeparator ? $row : $this->fillCells($row);
  502. }
  503. }
  504. }
  505. });
  506. }
  507. private function calculateRowCount(): int
  508. {
  509. $numberOfRows = \count(iterator_to_array($this->buildTableRows(array_merge($this->headers, [new TableSeparator()], $this->rows))));
  510. if ($this->headers) {
  511. ++$numberOfRows; // Add row for header separator
  512. }
  513. if (\count($this->rows) > 0) {
  514. ++$numberOfRows; // Add row for footer separator
  515. }
  516. return $numberOfRows;
  517. }
  518. /**
  519. * fill rows that contains rowspan > 1.
  520. *
  521. * @throws InvalidArgumentException
  522. */
  523. private function fillNextRows(array $rows, int $line): array
  524. {
  525. $unmergedRows = [];
  526. foreach ($rows[$line] as $column => $cell) {
  527. if (null !== $cell && !$cell instanceof TableCell && !is_scalar($cell) && !(\is_object($cell) && method_exists($cell, '__toString'))) {
  528. throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing "__toString()", "%s" given.', \gettype($cell)));
  529. }
  530. if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
  531. $nbLines = $cell->getRowspan() - 1;
  532. $lines = [$cell];
  533. if (strstr($cell, "\n")) {
  534. $lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
  535. $nbLines = \count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
  536. $rows[$line][$column] = new TableCell($lines[0], ['colspan' => $cell->getColspan()]);
  537. unset($lines[0]);
  538. }
  539. // create a two dimensional array (rowspan x colspan)
  540. $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, []), $unmergedRows);
  541. foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
  542. $value = $lines[$unmergedRowKey - $line] ?? '';
  543. $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, ['colspan' => $cell->getColspan()]);
  544. if ($nbLines === $unmergedRowKey - $line) {
  545. break;
  546. }
  547. }
  548. }
  549. }
  550. foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
  551. // we need to know if $unmergedRow will be merged or inserted into $rows
  552. if (isset($rows[$unmergedRowKey]) && \is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
  553. foreach ($unmergedRow as $cellKey => $cell) {
  554. // insert cell into row at cellKey position
  555. array_splice($rows[$unmergedRowKey], $cellKey, 0, [$cell]);
  556. }
  557. } else {
  558. $row = $this->copyRow($rows, $unmergedRowKey - 1);
  559. foreach ($unmergedRow as $column => $cell) {
  560. if (!empty($cell)) {
  561. $row[$column] = $unmergedRow[$column];
  562. }
  563. }
  564. array_splice($rows, $unmergedRowKey, 0, [$row]);
  565. }
  566. }
  567. return $rows;
  568. }
  569. /**
  570. * fill cells for a row that contains colspan > 1.
  571. */
  572. private function fillCells(iterable $row)
  573. {
  574. $newRow = [];
  575. foreach ($row as $column => $cell) {
  576. $newRow[] = $cell;
  577. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  578. foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
  579. // insert empty value at column position
  580. $newRow[] = '';
  581. }
  582. }
  583. }
  584. return $newRow ?: $row;
  585. }
  586. private function copyRow(array $rows, int $line): array
  587. {
  588. $row = $rows[$line];
  589. foreach ($row as $cellKey => $cellValue) {
  590. $row[$cellKey] = '';
  591. if ($cellValue instanceof TableCell) {
  592. $row[$cellKey] = new TableCell('', ['colspan' => $cellValue->getColspan()]);
  593. }
  594. }
  595. return $row;
  596. }
  597. /**
  598. * Gets number of columns by row.
  599. */
  600. private function getNumberOfColumns(array $row): int
  601. {
  602. $columns = \count($row);
  603. foreach ($row as $column) {
  604. $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
  605. }
  606. return $columns;
  607. }
  608. /**
  609. * Gets list of columns for the given row.
  610. */
  611. private function getRowColumns(array $row): array
  612. {
  613. $columns = range(0, $this->numberOfColumns - 1);
  614. foreach ($row as $cellKey => $cell) {
  615. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  616. // exclude grouped columns.
  617. $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
  618. }
  619. }
  620. return $columns;
  621. }
  622. /**
  623. * Calculates columns widths.
  624. */
  625. private function calculateColumnsWidth(iterable $rows)
  626. {
  627. for ($column = 0; $column < $this->numberOfColumns; ++$column) {
  628. $lengths = [];
  629. foreach ($rows as $row) {
  630. if ($row instanceof TableSeparator) {
  631. continue;
  632. }
  633. foreach ($row as $i => $cell) {
  634. if ($cell instanceof TableCell) {
  635. $textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
  636. $textLength = Helper::strlen($textContent);
  637. if ($textLength > 0) {
  638. $contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
  639. foreach ($contentColumns as $position => $content) {
  640. $row[$i + $position] = $content;
  641. }
  642. }
  643. }
  644. }
  645. $lengths[] = $this->getCellWidth($row, $column);
  646. }
  647. $this->effectiveColumnWidths[$column] = max($lengths) + Helper::strlen($this->style->getCellRowContentFormat()) - 2;
  648. }
  649. }
  650. private function getColumnSeparatorWidth(): int
  651. {
  652. return Helper::strlen(sprintf($this->style->getBorderFormat(), $this->style->getBorderChars()[3]));
  653. }
  654. private function getCellWidth(array $row, int $column): int
  655. {
  656. $cellWidth = 0;
  657. if (isset($row[$column])) {
  658. $cell = $row[$column];
  659. $cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  660. }
  661. $columnWidth = $this->columnWidths[$column] ?? 0;
  662. $cellWidth = max($cellWidth, $columnWidth);
  663. return isset($this->columnMaxWidths[$column]) ? min($this->columnMaxWidths[$column], $cellWidth) : $cellWidth;
  664. }
  665. /**
  666. * Called after rendering to cleanup cache data.
  667. */
  668. private function cleanup()
  669. {
  670. $this->effectiveColumnWidths = [];
  671. $this->numberOfColumns = null;
  672. }
  673. private static function initStyles(): array
  674. {
  675. $borderless = new TableStyle();
  676. $borderless
  677. ->setHorizontalBorderChars('=')
  678. ->setVerticalBorderChars(' ')
  679. ->setDefaultCrossingChar(' ')
  680. ;
  681. $compact = new TableStyle();
  682. $compact
  683. ->setHorizontalBorderChars('')
  684. ->setVerticalBorderChars(' ')
  685. ->setDefaultCrossingChar('')
  686. ->setCellRowContentFormat('%s')
  687. ;
  688. $styleGuide = new TableStyle();
  689. $styleGuide
  690. ->setHorizontalBorderChars('-')
  691. ->setVerticalBorderChars(' ')
  692. ->setDefaultCrossingChar(' ')
  693. ->setCellHeaderFormat('%s')
  694. ;
  695. $box = (new TableStyle())
  696. ->setHorizontalBorderChars('─')
  697. ->setVerticalBorderChars('│')
  698. ->setCrossingChars('┼', '┌', '┬', '┐', '┤', '┘', '┴', '└', '├')
  699. ;
  700. $boxDouble = (new TableStyle())
  701. ->setHorizontalBorderChars('═', '─')
  702. ->setVerticalBorderChars('║', '│')
  703. ->setCrossingChars('┼', '╔', '╤', '╗', '╢', '╝', '╧', '╚', '╟', '╠', '╪', '╣')
  704. ;
  705. return [
  706. 'default' => new TableStyle(),
  707. 'borderless' => $borderless,
  708. 'compact' => $compact,
  709. 'symfony-style-guide' => $styleGuide,
  710. 'box' => $box,
  711. 'box-double' => $boxDouble,
  712. ];
  713. }
  714. private function resolveStyle($name): TableStyle
  715. {
  716. if ($name instanceof TableStyle) {
  717. return $name;
  718. }
  719. if (isset(self::$styles[$name])) {
  720. return self::$styles[$name];
  721. }
  722. throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
  723. }
  724. }