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