-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTableView.php
More file actions
88 lines (68 loc) · 2.25 KB
/
TableView.php
File metadata and controls
88 lines (68 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
declare(strict_types=1);
namespace DragonCode\Benchmark\View;
use function array_keys;
use function array_map;
use function array_values;
use function implode;
use function max;
use function mb_str_pad;
use function mb_strlen;
class TableView extends View
{
public function show(array $data): void
{
$headers = $this->headers($data);
$widths = $this->columnWidths($headers, $data);
$this->writeHeaderLine($widths);
$this->writeLine($this->formatRow($headers, $widths));
$this->writeLine($this->separator($widths));
foreach ($data as $row) {
if ($row === [null]) {
$this->writeLine($this->separator($widths));
continue;
}
$this->writeLine($this->formatRow(array_values($row), $widths));
}
$this->writeFooterLine($widths);
}
protected function headers(array $data): array
{
return array_keys(array_values($data)[0]);
}
protected function columnWidths(array $headers, array $data): array
{
$widths = array_map(static fn ($header) => mb_strlen((string) $header), $headers);
foreach ($data as $row) {
foreach (array_values($row) as $i => $value) {
$widths[$i] = max($widths[$i], mb_strlen((string) $value));
}
}
return $widths;
}
protected function writeHeaderLine(array $widths): void
{
$this->writeLine(
$this->separator($widths, '┌', '┬', '┐')
);
}
protected function writeFooterLine(array $widths): void
{
$this->writeLine(
$this->separator($widths, '└', '┴', '┘')
);
}
protected function separator(array $widths, string $start = '├', string $divider = '┼', string $end = '┤'): string
{
$parts = array_map(static fn (int $w) => str_repeat('─', $w + 2), $widths);
return $start . implode($divider, $parts) . $end;
}
protected function formatRow(array $values, array $widths): string
{
$cells = [];
foreach ($values as $i => $value) {
$cells[] = ' ' . mb_str_pad((string) $value, $widths[$i]) . ' ';
}
return '│' . implode('│', $cells) . '│';
}
}