Debian Codegraph @

vendor/symfony/console/Helper/Table.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Console\Helper;
13
14 use Symfony\Component\Console\Exception\InvalidArgumentException;
15 use Symfony\Component\Console\Exception\RuntimeException;
16 use Symfony\Component\Console\Formatter\OutputFormatter;
17 use Symfony\Component\Console\Formatter\WrappableOutputFormatterInterface;
18 use Symfony\Component\Console\Output\ConsoleSectionOutput;
19 use Symfony\Component\Console\Output\OutputInterface;
20
21 /**
22 * Provides helpers to display a table.
23 *
24 * @author Fabien Potencier <[email protected]>
25 * @author Саша Стаменковић <[email protected]>
26 * @author Abdellatif Ait boudad <[email protected]>
27 * @author Max Grigorian <[email protected]>
28 * @author Dany Maillard <[email protected]>
29 */
30 class Table
31 {
32 private const SEPARATOR_TOP = 0;
33 private const SEPARATOR_TOP_BOTTOM = 1;
34 private const SEPARATOR_MID = 2;
35 private const SEPARATOR_BOTTOM = 3;
36 private const BORDER_OUTSIDE = 0;
37 private const BORDER_INSIDE = 1;
38 private const DISPLAY_ORIENTATION_DEFAULT = 'default';
39 private const DISPLAY_ORIENTATION_HORIZONTAL = 'horizontal';
40 private const DISPLAY_ORIENTATION_VERTICAL = 'vertical';
41
42 private ?string $headerTitle = null;
43 private ?string $footerTitle = null;
44 private array $headers = [];
45 private array $rows = [];
46 private array $effectiveColumnWidths = [];
47 private int $numberOfColumns;
48 private TableStyle $style;
49 private array $columnStyles = [];
50 private array $columnWidths = [];
51 private array $columnMaxWidths = [];
52 private bool $rendered = false;
53 private string $displayOrientation = self::DISPLAY_ORIENTATION_DEFAULT;
54
55 private static array $styles;
56
57 public function __construct(
58 private OutputInterface $output,
59 ) {
60 self::$styles ??= self::initStyles();
61
62 $this->setStyle('default');
63 }
64
65 /**
66 * Sets a style definition.
67 */
68 public static function setStyleDefinition(string $name, TableStyle $style): void
69 {
70 self::$styles ??= self::initStyles();
71
72 self::$styles[$name] = $style;
73 }
74
75 /**
76 * Gets a style definition by name.
77 */
78 public static function getStyleDefinition(string $name): TableStyle
79 {
80 self::$styles ??= self::initStyles();
81
82 return self::$styles[$name] ?? throw new InvalidArgumentException(\sprintf('Style "%s" is not defined.', $name));
83 }
84
85 /**
86 * Sets table style.
87 *
88 * @return $this
89 */
90 public function setStyle(TableStyle|string $name): static
91 {
92 $this->style = $this->resolveStyle($name);
93
94 return $this;
95 }
96
97 /**
98 * Gets the current table style.
99 */
100 public function getStyle(): TableStyle
101 {
102 return $this->style;
103 }
104
105 /**
106 * Sets table column style.
107 *
108 * @param TableStyle|string $name The style name or a TableStyle instance
109 *
110 * @return $this
111 */
112 public function setColumnStyle(int $columnIndex, TableStyle|string $name): static
113 {
114 $this->columnStyles[$columnIndex] = $this->resolveStyle($name);
115
116 return $this;
117 }
118
119 /**
120 * Gets the current style for a column.
121 *
122 * If style was not set, it returns the global table style.
123 */
124 public function getColumnStyle(int $columnIndex): TableStyle
125 {
126 return $this->columnStyles[$columnIndex] ?? $this->getStyle();
127 }
128
129 /**
130 * Sets the minimum width of a column.
131 *
132 * @return $this
133 */
134 public function setColumnWidth(int $columnIndex, int $width): static
135 {
136 $this->columnWidths[$columnIndex] = $width;
137
138 return $this;
139 }
140
141 /**
142 * Sets the minimum width of all columns.
143 *
144 * @return $this
145 */
146 public function setColumnWidths(array $widths): static
147 {
148 $this->columnWidths = [];
149 foreach ($widths as $index => $width) {
150 $this->setColumnWidth($index, $width);
151 }
152
153 return $this;
154 }
155
156 /**
157 * Sets the maximum width of a column.
158 *
159 * Any cell within this column which contents exceeds the specified width will be wrapped into multiple lines, while
160 * formatted strings are preserved.
161 *
162 * @return $this
163 */
164 public function setColumnMaxWidth(int $columnIndex, int $width): static
165 {
166 if (!$this->output->getFormatter() instanceof WrappableOutputFormatterInterface) {
167 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())));
168 }
169
170 $this->columnMaxWidths[$columnIndex] = $width;
171
172 return $this;
173 }
174
175 /**
176 * @return $this
177 */
178 public function setHeaders(array $headers): static
179 {
180 $headers = array_values($headers);
181 if ($headers && !\is_array($headers[0])) {
182 $headers = [$headers];
183 }
184
185 $this->headers = $headers;
186
187 return $this;
188 }
189
190 /**
191 * @return $this
192 */
193 public function setRows(array $rows): static
194 {
195 $this->rows = [];
196
197 return $this->addRows($rows);
198 }
199
200 /**
201 * @return $this
202 */
203 public function addRows(array $rows): static
204 {
205 foreach ($rows as $row) {
206 $this->addRow($row);
207 }
208
209 return $this;
210 }
211
212 /**
213 * @return $this
214 */
215 public function addRow(TableSeparator|array $row): static
216 {
217 if ($row instanceof TableSeparator) {
218 $this->rows[] = $row;
219
220 return $this;
221 }
222
223 $this->rows[] = array_values($row);
224
225 return $this;
226 }
227
228 /**
229 * Adds a row to the table, and re-renders the table.
230 *
231 * @return $this
232 */
233 public function appendRow(TableSeparator|array $row): static
234 {
235 if (!$this->output instanceof ConsoleSectionOutput) {
236 throw new RuntimeException(\sprintf('Output should be an instance of "%s" when calling "%s".', ConsoleSectionOutput::class, __METHOD__));
237 }
238
239 if ($this->rendered) {
240 $this->output->clear($this->calculateRowCount());
241 }
242
243 $this->addRow($row);
244 $this->render();
245
246 return $this;
247 }
248
249 /**
250 * @return $this
251 */
252 public function setRow(int|string $column, array $row): static
253 {
254 $this->rows[$column] = $row;
255
256 return $this;
257 }
258
259 /**
260 * @return $this
261 */
262 public function setHeaderTitle(?string $title): static
263 {
264 $this->headerTitle = $title;
265
266 return $this;
267 }
268
269 /**
270 * @return $this
271 */
272 public function setFooterTitle(?string $title): static
273 {
274 $this->footerTitle = $title;
275
276 return $this;
277 }
278
279 /**
280 * @return $this
281 */
282 public function setHorizontal(bool $horizontal = true): static
283 {
284 $this->displayOrientation = $horizontal ? self::DISPLAY_ORIENTATION_HORIZONTAL : self::DISPLAY_ORIENTATION_DEFAULT;
285
286 return $this;
287 }
288
289 /**
290 * @return $this
291 */
292 public function setVertical(bool $vertical = true): static
293 {
294 $this->displayOrientation = $vertical ? self::DISPLAY_ORIENTATION_VERTICAL : self::DISPLAY_ORIENTATION_DEFAULT;
295
296 return $this;
297 }
298
299 /**
300 * Renders table to output.
301 *
302 * Example:
303 *
304 * +---------------+-----------------------+------------------+
305 * | ISBN | Title | Author |
306 * +---------------+-----------------------+------------------+
307 * | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
308 * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
309 * | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
310 * +---------------+-----------------------+------------------+
311 */
312 public function render(): void
313 {
314 $divider = new TableSeparator();
315 $isCellWithColspan = static fn ($cell) => $cell instanceof TableCell && $cell->getColspan() >= 2;
316
317 $horizontal = self::DISPLAY_ORIENTATION_HORIZONTAL === $this->displayOrientation;
318 $vertical = self::DISPLAY_ORIENTATION_VERTICAL === $this->displayOrientation;
319
320 $rows = [];
321 if ($horizontal) {
322 foreach ($this->headers[0] ?? [] as $i => $header) {
323 $rows[$i] = [$header];
324 foreach ($this->rows as $row) {
325 if ($row instanceof TableSeparator) {
326 continue;
327 }
328 if (isset($row[$i])) {
329 $rows[$i][] = $row[$i];
330 } elseif ($isCellWithColspan($rows[$i][0])) {
331 // Noop, there is a "title"
332 } else {
333 $rows[$i][] = null;
334 }
335 }
336 }
337 } elseif ($vertical) {
338 $formatter = $this->output->getFormatter();
339 $maxHeaderLength = array_reduce($this->headers[0] ?? [], static fn ($max, $header) => max($max, Helper::width(Helper::removeDecoration($formatter, $header))), 0);
340
341 foreach ($this->rows as $row) {
342 if ($row instanceof TableSeparator) {
343 continue;
344 }
345
346 if ($rows) {
347 $rows[] = [$divider];
348 }
349
350 $containsColspan = false;
351 foreach ($row as $cell) {
352 if ($containsColspan = $isCellWithColspan($cell)) {
353 break;
354 }
355 }
356
357 $headers = $this->headers[0] ?? [];
358 $maxRows = max(\count($headers), \count($row));
359 for ($i = 0; $i < $maxRows; ++$i) {
360 $cell = (string) ($row[$i] ?? '');
361
362 $eol = str_contains($cell, "\r\n") ? "\r\n" : "\n";
363 $parts = explode($eol, $cell);
364 foreach ($parts as $idx => $part) {
365 if ($headers && !$containsColspan) {
366 if (0 === $idx) {
367 $rows[] = [\sprintf(
368 '<comment>%s%s</>: %s',
369 str_repeat(' ', $maxHeaderLength - Helper::width(Helper::removeDecoration($formatter, $headers[$i] ?? ''))),
370 $headers[$i] ?? '',
371 $part
372 )];
373 } else {
374 $rows[] = [\sprintf(
375 '%s %s',
376 str_pad('', $maxHeaderLength, ' ', \STR_PAD_LEFT),
377 $part
378 )];
379 }
380 } elseif ('' !== $cell) {
381 $rows[] = [$part];
382 }
383 }
384 }
385 }
386 } else {
387 $rows = array_merge($this->headers, [$divider], $this->rows);
388 }
389
390 $this->calculateNumberOfColumns($rows);
391
392 $rowGroups = $this->buildTableRows($rows);
393 $this->calculateColumnsWidth($rowGroups);
394
395 $isHeader = !$horizontal;
396 $isFirstRow = $horizontal;
397 $hasTitle = (bool) $this->headerTitle;
398
399 foreach ($rowGroups as $rowGroup) {
400 $isHeaderSeparatorRendered = false;
401
402 foreach ($rowGroup as $row) {
403 if ($divider === $row) {
404 $isHeader = false;
405 $isFirstRow = true;
406
407 continue;
408 }
409
410 if ($row instanceof TableSeparator) {
411 $this->renderRowSeparator();
412
413 continue;
414 }
415
416 if (!$row) {
417 continue;
418 }
419
420 if ($isHeader && !$isHeaderSeparatorRendered && $this->style->displayOutsideBorder()) {
421 $this->renderRowSeparator(
422 self::SEPARATOR_TOP,
423 $hasTitle ? $this->headerTitle : null,
424 $hasTitle ? $this->style->getHeaderTitleFormat() : null
425 );
426 $hasTitle = false;
427 $isHeaderSeparatorRendered = true;
428 }
429
430 if ($isFirstRow) {
431 $this->renderRowSeparator(
432 $horizontal ? self::SEPARATOR_TOP : self::SEPARATOR_TOP_BOTTOM,
433 $hasTitle ? $this->headerTitle : null,
434 $hasTitle ? $this->style->getHeaderTitleFormat() : null
435 );
436 $isFirstRow = false;
437 $hasTitle = false;
438 }
439
440 if ($vertical) {
441 $isHeader = false;
442 $isFirstRow = false;
443 }
444
445 if ($horizontal) {
446 $this->renderRow($row, $this->style->getCellRowFormat(), $this->style->getCellHeaderFormat());
447 } else {
448 $this->renderRow($row, $isHeader ? $this->style->getCellHeaderFormat() : $this->style->getCellRowFormat());
449 }
450 }
451 }
452
453 if ($this->getStyle()->displayOutsideBorder()) {
454 $this->renderRowSeparator(self::SEPARATOR_BOTTOM, $this->footerTitle, $this->style->getFooterTitleFormat());
455 }
456
457 $this->cleanup();
458 $this->rendered = true;
459 }
460
461 /**
462 * Renders horizontal header separator.
463 *
464 * Example:
465 *
466 * +-----+-----------+-------+
467 */
468 private function renderRowSeparator(int $type = self::SEPARATOR_MID, ?string $title = null, ?string $titleFormat = null): void
469 {
470 if (!$count = $this->numberOfColumns) {
471 return;
472 }
473
474 $borders = $this->style->getBorderChars();
475 if (!$borders[0] && !$borders[2] && !$this->style->getCrossingChar()) {
476 return;
477 }
478
479 $crossings = $this->style->getCrossingChars();
480 if (self::SEPARATOR_MID === $type) {
481 [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[2], $crossings[8], $crossings[0], $crossings[4]];
482 } elseif (self::SEPARATOR_TOP === $type) {
483 [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[1], $crossings[2], $crossings[3]];
484 } elseif (self::SEPARATOR_TOP_BOTTOM === $type) {
485 [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[9], $crossings[10], $crossings[11]];
486 } else {
487 [$horizontal, $leftChar, $midChar, $rightChar] = [$borders[0], $crossings[7], $crossings[6], $crossings[5]];
488 }
489
490 $markup = $leftChar;
491 for ($column = 0; $column < $count; ++$column) {
492 $markup .= str_repeat($horizontal, $this->effectiveColumnWidths[$column]);
493 $markup .= $column === $count - 1 ? $rightChar : $midChar;
494 }
495
496 if (null !== $title) {
497 $titleLength = Helper::width(Helper::removeDecoration($formatter = $this->output->getFormatter(), $formattedTitle = \sprintf($titleFormat, $title)));
498 $markupLength = Helper::width($markup);
499 if ($titleLength > $limit = $markupLength - 4) {
500 $titleLength = $limit;
501 $formatLength = Helper::width(Helper::removeDecoration($formatter, \sprintf($titleFormat, '')));
502 $formattedTitle = \sprintf($titleFormat, Helper::substr($title, 0, $limit - $formatLength - 3).'...');
503 }
504
505 $titleStart = intdiv($markupLength - $titleLength, 2);
506 if (false === mb_detect_encoding($markup, null, true)) {
507 $markup = substr_replace($markup, $formattedTitle, $titleStart, $titleLength);
508 } else {
509 $markup = mb_substr($markup, 0, $titleStart).$formattedTitle.mb_substr($markup, $titleStart + $titleLength);
510 }
511 }
512
513 $this->output->writeln(\sprintf($this->style->getBorderFormat(), $markup));
514 }
515
516 /**
517 * Renders vertical column separator.
518 */
519 private function renderColumnSeparator(int $type = self::BORDER_OUTSIDE): string
520 {
521 $borders = $this->style->getBorderChars();
522
523 return \sprintf($this->style->getBorderFormat(), self::BORDER_OUTSIDE === $type ? $borders[1] : $borders[3]);
524 }
525
526 /**
527 * Renders table row.
528 *
529 * Example:
530 *
531 * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
532 */
533 private function renderRow(array $row, string $cellFormat, ?string $firstCellFormat = null): void
534 {
535 $rowContent = $this->renderColumnSeparator(self::BORDER_OUTSIDE);
536 $columns = $this->getRowColumns($row);
537 $last = \count($columns) - 1;
538 foreach ($columns as $i => $column) {
539 if ($firstCellFormat && 0 === $i) {
540 $rowContent .= $this->renderCell($row, $column, $firstCellFormat);
541 } else {
542 $rowContent .= $this->renderCell($row, $column, $cellFormat);
543 }
544 $rowContent .= $this->renderColumnSeparator($last === $i ? self::BORDER_OUTSIDE : self::BORDER_INSIDE);
545 }
546 $this->output->writeln($rowContent);
547 }
548
549 /**
550 * Renders table cell with padding.
551 */
552 private function renderCell(array $row, int $column, string $cellFormat): string
553 {
554 $cell = $row[$column] ?? '';
555 $width = $this->effectiveColumnWidths[$column];
556 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
557 // add the width of the following columns(numbers of colspan).
558 foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
559 $width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn];
560 }
561 }
562
563 // str_pad won't work properly with multi-byte strings, we need to fix the padding
564 $width += \strlen($cell) - Helper::width($cell) - substr_count($cell, "\0");
565 $style = $this->getColumnStyle($column);
566
567 if ($cell instanceof TableSeparator) {
568 return \sprintf($style->getBorderFormat(), str_repeat($style->getBorderChars()[2], $width));
569 }
570
571 $width += Helper::length($cell) - Helper::length(Helper::removeDecoration($this->output->getFormatter(), $cell));
572 $content = \sprintf($style->getCellRowContentFormat(), $cell);
573
574 $padType = $style->getPadType();
575 if ($cell instanceof TableCell && $cell->getStyle() instanceof TableCellStyle) {
576 $isNotStyledByTag = !preg_match('/^<(\w+|(\w+=[\w,]+;?)*)>.+<\/(\w+|(\w+=\w+;?)*)?>$/', $cell);
577 if ($isNotStyledByTag) {
578 $cellFormat = $cell->getStyle()->getCellFormat();
579 if (!\is_string($cellFormat)) {
580 $tag = http_build_query($cell->getStyle()->getTagOptions(), '', ';');
581 $cellFormat = '<'.$tag.'>%s</>';
582 }
583
584 if (str_contains($content, '</>')) {
585 $content = str_replace('</>', '', $content);
586 $width -= 3;
587 }
588 if (str_contains($content, '<fg=default;bg=default>')) {
589 $content = str_replace('<fg=default;bg=default>', '', $content);
590 $width -= \strlen('<fg=default;bg=default>');
591 }
592 }
593
594 $padType = $cell->getStyle()->getPadByAlign();
595 }
596
597 return \sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $padType));
598 }
599
600 /**
601 * Calculate number of columns for this table.
602 */
603 private function calculateNumberOfColumns(array $rows): void
604 {
605 $columns = [0];
606 foreach ($rows as $row) {
607 if ($row instanceof TableSeparator) {
608 continue;
609 }
610
611 $columns[] = $this->getNumberOfColumns($row);
612 }
613
614 $this->numberOfColumns = max($columns);
615 }
616
617 private function buildTableRows(array $rows): TableRows
618 {
619 /** @var WrappableOutputFormatterInterface $formatter */
620 $formatter = $this->output->getFormatter();
621 $unmergedRows = [];
622 for ($rowKey = 0; $rowKey < \count($rows); ++$rowKey) {
623 $rows = $this->fillNextRows($rows, $rowKey);
624
625 // Remove any new line breaks and replace it with a new line
626 foreach ($rows[$rowKey] as $column => $cell) {
627 $colspan = $cell instanceof TableCell ? $cell->getColspan() : 1;
628
629 $minWrappedWidth = 0;
630 $widthApplied = [];
631 $lengthColumnBorder = $this->getColumnSeparatorWidth() + Helper::width($this->style->getCellRowContentFormat()) - 2;
632 for ($i = $column; $i < ($column + $colspan); ++$i) {
633 if (isset($this->columnMaxWidths[$i])) {
634 $minWrappedWidth += $this->columnMaxWidths[$i];
635 $widthApplied[] = ['type' => 'max', 'column' => $i];
636 } elseif (($this->columnWidths[$i] ?? 0) > 0 && $colspan > 1) {
637 $minWrappedWidth += $this->columnWidths[$i];
638 $widthApplied[] = ['type' => 'min', 'column' => $i];
639 }
640 }
641 if (1 === \count($widthApplied)) {
642 if ($colspan > 1) {
643 $minWrappedWidth *= $colspan; // previous logic
644 }
645 } elseif (\count($widthApplied) > 1) {
646 $minWrappedWidth += (\count($widthApplied) - 1) * $lengthColumnBorder;
647 }
648
649 $cellWidth = Helper::width(Helper::removeDecoration($formatter, $cell));
650 if ($minWrappedWidth && $cellWidth > $minWrappedWidth) {
651 $cell = $formatter->formatAndWrap($cell, $minWrappedWidth);
652 }
653 // update minimal columnWidths for spanned columns
654 if ($colspan > 1 && $minWrappedWidth > 0) {
655 $columnsMinWidthProcessed = [];
656 $cellWidth = min($cellWidth, $minWrappedWidth);
657 foreach ($widthApplied as $item) {
658 if ('max' === $item['type'] && $cellWidth >= $this->columnMaxWidths[$item['column']]) {
659 $minWidthColumn = $this->columnMaxWidths[$item['column']];
660 $this->columnWidths[$item['column']] = $minWidthColumn;
661 $columnsMinWidthProcessed[$item['column']] = true;
662 $cellWidth -= $minWidthColumn + $lengthColumnBorder;
663 }
664 }
665 for ($i = $column; $i < ($column + $colspan); ++$i) {
666 if (isset($columnsMinWidthProcessed[$i])) {
667 continue;
668 }
669 $this->columnWidths[$i] = $cellWidth + $lengthColumnBorder;
670 }
671 }
672 if (!str_contains($cell ?? '', "\n")) {
673 continue;
674 }
675 $eol = str_contains($cell ?? '', "\r\n") ? "\r\n" : "\n";
676 $escaped = implode($eol, array_map(OutputFormatter::escapeTrailingBackslash(...), explode($eol, $cell)));
677 $cell = $cell instanceof TableCell ? new TableCell($escaped, ['colspan' => $cell->getColspan()]) : $escaped;
678 $lines = explode($eol, str_replace($eol, '<fg=default;bg=default></>'.$eol, $cell));
679 foreach ($lines as $lineKey => $line) {
680 if ($colspan > 1) {
681 $line = new TableCell($line, ['colspan' => $colspan]);
682 }
683 if (0 === $lineKey) {
684 $rows[$rowKey][$column] = $line;
685 } else {
686 if (!\array_key_exists($rowKey, $unmergedRows) || !\array_key_exists($lineKey, $unmergedRows[$rowKey])) {
687 $unmergedRows[$rowKey][$lineKey] = $this->copyRow($rows, $rowKey);
688 }
689 $unmergedRows[$rowKey][$lineKey][$column] = $line;
690 }
691 }
692 }
693 }
694
695 return new TableRows(function () use ($rows, $unmergedRows): \Traversable {
696 foreach ($rows as $rowKey => $row) {
697 $rowGroup = [$row instanceof TableSeparator ? $row : $this->fillCells($row)];
698
699 if (isset($unmergedRows[$rowKey])) {
700 foreach ($unmergedRows[$rowKey] as $row) {
701 $rowGroup[] = $row instanceof TableSeparator ? $row : $this->fillCells($row);
702 }
703 }
704 yield $rowGroup;
705 }
706 });
707 }
708
709 private function calculateRowCount(): int
710 {
711 $numberOfRows = \count(iterator_to_array($this->buildTableRows(array_merge($this->headers, [new TableSeparator()], $this->rows))));
712
713 if ($this->headers) {
714 ++$numberOfRows; // Add row for header separator
715 }
716
717 if ($this->rows) {
718 ++$numberOfRows; // Add row for footer separator
719 }
720
721 return $numberOfRows;
722 }
723
724 /**
725 * fill rows that contains rowspan > 1.
726 *
727 * @throws InvalidArgumentException
728 */
729 private function fillNextRows(array $rows, int $line): array
730 {
731 $unmergedRows = [];
732 foreach ($rows[$line] as $column => $cell) {
733 if (null !== $cell && !$cell instanceof TableCell && !\is_scalar($cell) && !$cell instanceof \Stringable) {
734 throw new InvalidArgumentException(\sprintf('A cell must be a TableCell, a scalar or an object implementing "__toString()", "%s" given.', get_debug_type($cell)));
735 }
736 if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
737 $nbLines = $cell->getRowspan() - 1;
738 $lines = [$cell];
739 if (str_contains($cell, "\n")) {
740 $eol = str_contains($cell, "\r\n") ? "\r\n" : "\n";
741 $lines = explode($eol, str_replace($eol, '<fg=default;bg=default>'.$eol.'</>', $cell));
742 $nbLines = \count($lines) > $nbLines ? substr_count($cell, $eol) : $nbLines;
743
744 $rows[$line][$column] = new TableCell($lines[0], ['colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]);
745 unset($lines[0]);
746 }
747
748 // create a two dimensional array (rowspan x colspan)
749 $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, []), $unmergedRows);
750 foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
751 $value = $lines[$unmergedRowKey - $line] ?? '';
752 $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, ['colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]);
753 if ($nbLines === $unmergedRowKey - $line) {
754 break;
755 }
756 }
757 }
758 }
759
760 foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
761 // we need to know if $unmergedRow will be merged or inserted into $rows
762 if (isset($rows[$unmergedRowKey]) && \is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRow) <= $this->numberOfColumns)) {
763 foreach ($unmergedRow as $cellKey => $cell) {
764 // insert cell into row at cellKey position
765 array_splice($rows[$unmergedRowKey], $cellKey, 0, [$cell]);
766 }
767 } else {
768 $row = $this->copyRow($rows, $unmergedRowKey - 1);
769 foreach ($unmergedRow as $column => $cell) {
770 if ($cell) {
771 $row[$column] = $cell;
772 }
773 }
774 array_splice($rows, $unmergedRowKey, 0, [$row]);
775 }
776 }
777
778 return $rows;
779 }
780
781 /**
782 * fill cells for a row that contains colspan > 1.
783 */
784 private function fillCells(iterable $row): iterable
785 {
786 $newRow = [];
787
788 foreach ($row as $column => $cell) {
789 $newRow[] = $cell;
790 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
791 foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
792 // insert empty value at column position
793 $newRow[] = '';
794 }
795 }
796 }
797
798 return $newRow ?: $row;
799 }
800
801 private function copyRow(array $rows, int $line): array
802 {
803 $row = $rows[$line];
804 foreach ($row as $cellKey => $cellValue) {
805 $row[$cellKey] = '';
806 if ($cellValue instanceof TableCell) {
807 $row[$cellKey] = new TableCell('', ['colspan' => $cellValue->getColspan()]);
808 }
809 }
810
811 return $row;
812 }
813
814 /**
815 * Gets number of columns by row.
816 */
817 private function getNumberOfColumns(array $row): int
818 {
819 $columns = \count($row);
820 foreach ($row as $column) {
821 $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
822 }
823
824 return $columns;
825 }
826
827 /**
828 * Gets list of columns for the given row.
829 */
830 private function getRowColumns(array $row): array
831 {
832 $columns = range(0, $this->numberOfColumns - 1);
833 foreach ($row as $cellKey => $cell) {
834 if ($cell instanceof TableCell && $cell->getColspan() > 1) {
835 // exclude grouped columns.
836 $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
837 }
838 }
839
840 return $columns;
841 }
842
843 /**
844 * Calculates columns widths.
845 */
846 private function calculateColumnsWidth(iterable $groups): void
847 {
848 for ($column = 0; $column < $this->numberOfColumns; ++$column) {
849 $lengths = [];
850 foreach ($groups as $group) {
851 foreach ($group as $row) {
852 if ($row instanceof TableSeparator) {
853 continue;
854 }
855
856 foreach ($row as $i => $cell) {
857 if ($cell instanceof TableCell) {
858 $textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
859 $textLength = Helper::width($textContent);
860 if ($textLength > 0) {
861 $contentColumns = mb_str_split($textContent, ceil($textLength / $cell->getColspan()));
862 foreach ($contentColumns as $position => $content) {
863 $row[$i + $position] = $content;
864 }
865 }
866 }
867 }
868
869 $lengths[] = $this->getCellWidth($row, $column);
870 }
871 }
872
873 $this->effectiveColumnWidths[$column] = max($lengths) + Helper::width($this->style->getCellRowContentFormat()) - 2;
874 }
875 }
876
877 private function getColumnSeparatorWidth(): int
878 {
879 return Helper::width(\sprintf($this->style->getBorderFormat(), $this->style->getBorderChars()[3]));
880 }
881
882 private function getCellWidth(array $row, int $column): int
883 {
884 $cellWidth = 0;
885
886 if (isset($row[$column])) {
887 $cell = $row[$column];
888 $cellWidth = Helper::width(Helper::removeDecoration($this->output->getFormatter(), $cell));
889 }
890
891 $columnWidth = $this->columnWidths[$column] ?? 0;
892 $cellWidth = max($cellWidth, $columnWidth);
893
894 return isset($this->columnMaxWidths[$column]) ? min($this->columnMaxWidths[$column], $cellWidth) : $cellWidth;
895 }
896
897 /**
898 * Called after rendering to cleanup cache data.
899 */
900 private function cleanup(): void
901 {
902 $this->effectiveColumnWidths = [];
903 unset($this->numberOfColumns);
904 }
905
906 /**
907 * @return array<string, TableStyle>
908 */
909 private static function initStyles(): array
910 {
911 $markdown = new TableStyle();
912 $markdown
913 ->setDefaultCrossingChar('|')
914 ->setDisplayOutsideBorder(false)
915 ;
916
917 $borderless = new TableStyle();
918 $borderless
919 ->setHorizontalBorderChars('=')
920 ->setVerticalBorderChars(' ')
921 ->setDefaultCrossingChar(' ')
922 ;
923
924 $compact = new TableStyle();
925 $compact
926 ->setHorizontalBorderChars('')
927 ->setVerticalBorderChars('')
928 ->setDefaultCrossingChar('')
929 ->setCellRowContentFormat('%s ')
930 ;
931
932 $styleGuide = new TableStyle();
933 $styleGuide
934 ->setHorizontalBorderChars('-')
935 ->setVerticalBorderChars(' ')
936 ->setDefaultCrossingChar(' ')
937 ->setCellHeaderFormat('%s')
938 ;
939
940 $box = (new TableStyle())
941 ->setHorizontalBorderChars('─')
942 ->setVerticalBorderChars('│')
943 ->setCrossingChars('┼', '┌', '┬', '┐', '┤', '┘', '┴', '└', '├')
944 ;
945
946 $boxDouble = (new TableStyle())
947 ->setHorizontalBorderChars('═', '─')
948 ->setVerticalBorderChars('║', '│')
949 ->setCrossingChars('┼', '╔', '╤', '╗', '╢', '╝', '╧', '╚', '╟', '╠', '╪', '╣')
950 ;
951
952 return [
953 'default' => new TableStyle(),
954 'markdown' => $markdown,
955 'borderless' => $borderless,
956 'compact' => $compact,
957 'symfony-style-guide' => $styleGuide,
958 'box' => $box,
959 'box-double' => $boxDouble,
960 ];
961 }
962
963 private function resolveStyle(TableStyle|string $name): TableStyle
964 {
965 if ($name instanceof TableStyle) {
966 return $name;
967 }
968
969 return self::$styles[$name] ?? throw new InvalidArgumentException(\sprintf('Style "%s" is not defined.', $name));
970 }
971 }