Table.php 25 KB

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