Table.php 25 KB

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