1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Outline; |
4
|
|
|
|
5
|
|
|
class Renderer |
6
|
|
|
{ |
7
|
|
|
/** @var array */ |
8
|
|
|
protected $lines; |
9
|
|
|
|
10
|
|
|
public function __construct(array $lines) |
11
|
|
|
{ |
12
|
|
|
$this->lines = $lines; |
13
|
|
|
} |
14
|
|
|
|
15
|
|
|
public function getRendered(): string |
16
|
|
|
{ |
17
|
|
|
$lines = $this->renderLines(); |
18
|
|
|
|
19
|
|
|
return str_replace('{{ outline }}', $lines, file_get_contents(__DIR__.'/index.twig')); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
protected function renderLines() |
23
|
|
|
{ |
24
|
|
|
$rendered = []; |
25
|
|
|
|
26
|
|
|
$maximumLineLength = $this->getMaximumLineLength($this->lines); |
27
|
|
|
|
28
|
|
|
foreach ($this->lines as $lineNumber => $line) { |
29
|
|
|
$lineNumber = str_pad($lineNumber, 3, '0', STR_PAD_LEFT); |
30
|
|
|
|
31
|
|
|
$rendered[] = $this->renderLine($line, $maximumLineLength, $lineNumber); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
return implode(PHP_EOL, $rendered); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
protected function renderLine(?array $line, int $maximumLineLength, string $lineNumber): string |
38
|
|
|
{ |
39
|
|
|
if (!$line) { |
40
|
|
|
return "<div>{$lineNumber}: </div>"; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$renderedLine = array_map(function ($characterValue) use ($maximumLineLength) { |
44
|
|
|
$class = 'code'; |
45
|
|
|
|
46
|
|
|
if ($characterValue < 0) { |
47
|
|
|
$class .= ' indent'; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$color = $this->getColor($characterValue, $maximumLineLength); |
51
|
|
|
|
52
|
|
|
return "<span class=\"{$class}\" style=\"background-color:{$color}\"> </span>"; |
53
|
|
|
}, $line); |
54
|
|
|
|
55
|
|
|
return "<div>{$lineNumber}: ".implode('', $renderedLine).'</div>'; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
protected function getMaximumLineLength(array $lines): int |
59
|
|
|
{ |
60
|
|
|
$maximumLineLenghts = []; |
61
|
|
|
|
62
|
|
|
foreach ($lines as $line) { |
63
|
|
|
if (!$line) { |
64
|
|
|
continue; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$maximumLineLenghts[] = max($line); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return max($maximumLineLenghts); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
protected function getColor(int $value, int $max): string |
74
|
|
|
{ |
75
|
|
|
$modifier = 1 - ($value / $max); |
76
|
|
|
|
77
|
|
|
$gray = (245 * $modifier); |
78
|
|
|
|
79
|
|
|
return $this->getRgbHex($gray, $gray, $gray); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
protected function getRgbHex(int $red, int $green, int $blue) |
83
|
|
|
{ |
84
|
|
|
$colors = array_map(function ($color) { |
85
|
|
|
return str_pad(dechex($color), 2, '0', STR_PAD_LEFT); |
86
|
|
|
}, [$red, $green, $blue]); |
87
|
|
|
|
88
|
|
|
return '#'.implode('', $colors); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|