Repository navigation
Expand file tree
/
Copy pathTableBuilder.php
More file actions
75 lines (58 loc) · 1.62 KB
/
Copy pathTableBuilder.php
File metadata and controls
75 lines (58 loc) · 1.62 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
<?php
declare(strict_types=1);
namespace Premier\MarkdownBuilder\Block;
use Premier\MarkdownBuilder\BlockInterface;
final class TableBuilder implements BlockInterface
{
/**
* @var array<int, string>
*/
private array $headers;
/**
* @var array<int, array<int, string>>
*/
private array $rows;
/**
* @param array<int, string> $headers
* @param array<int, array<int, string>> $rows
*/
public function __construct(array $headers, array $rows = [])
{
$this->headers = $headers;
$this->rows = $rows;
}
public function __toString(): string
{
return $this->getMarkdown();
}
public function addRow(string ...$row): self
{
$this->rows[] = $row;
return $this;
}
/**
* @param callable(array<int, string>, array<int, string>): int $callback
*/
public function sort(callable $callback): self
{
\usort($this->rows, $callback);
return $this;
}
public function getMarkdown(): string
{
$markdown = '';
$headers = $this->headers;
$separator = \array_map(static function (string $header): string {
return \str_repeat('-', \mb_strlen($header));
}, $headers);
$markdown .= \implode(' | ', $headers).PHP_EOL;
$markdown .= \implode(' | ', $separator).PHP_EOL;
foreach ($this->rows as $key => $row) {
$markdown .= \implode(' | ', $row);
if (\array_key_last($this->rows) !== $key) {
$markdown .= PHP_EOL;
}
}
return $markdown;
}
}