1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the CLI-SYNTAX package. |
7
|
|
|
* |
8
|
|
|
* (c) Jitendra Adhikari <[email protected]> |
9
|
|
|
* <https://github.com/adhocore> |
10
|
|
|
* |
11
|
|
|
* Licensed under MIT license. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Ahc\CliSyntax; |
15
|
|
|
|
16
|
|
|
class Highlighter extends Pretty |
17
|
|
|
{ |
18
|
|
|
/** @var string Output string */ |
19
|
|
|
protected $out = ''; |
20
|
|
|
|
21
|
|
|
public function __toString(): string |
22
|
|
|
{ |
23
|
|
|
return $this->highlight(); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function highlight(string $code = null, array $options = []): string |
27
|
|
|
{ |
28
|
|
|
$this->setOptions($options); |
29
|
|
|
|
30
|
|
|
$this->parse($code ?? $this->code); |
31
|
|
|
|
32
|
|
|
return \trim($this->out, "\n") . "\n"; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
protected function doReset() |
36
|
|
|
{ |
37
|
|
|
$this->out = ''; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
protected function visit(\DOMNode $el) |
41
|
|
|
{ |
42
|
|
|
$type = $el instanceof \DOMElement ? $el->getAttribute('data-type') : 'raw'; |
43
|
|
|
$text = \str_replace([' ', '<', '>'], [' ', '<', '>'], $el->textContent); |
44
|
|
|
|
45
|
|
|
$lastLine = 0; |
|
|
|
|
46
|
|
|
$lines = \explode("\n", $text); |
47
|
|
|
foreach ($lines as $i => $line) { |
48
|
|
|
$this->out .= $this->formatLine($type, $line); |
49
|
|
|
|
50
|
|
|
if (isset($lines[$i + 1])) { |
51
|
|
|
$this->out .= "\n"; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$this->lengths[$this->lineNo++] = \strlen($line); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
protected function formatLine(string $type, string $line) |
59
|
|
|
{ |
60
|
|
|
static $formats = [ |
61
|
|
|
'comment' => "\033[0;34;40m%s\033[0m", |
62
|
|
|
'default' => "\033[0;32;40m%s\033[0m", |
63
|
|
|
'keyword' => "\033[0;31;40m%s\033[0m", |
64
|
|
|
'string' => "\033[0;33;40m%s\033[0m", |
65
|
|
|
'lineno' => "\033[2;36;40m%s\033[0m", |
66
|
|
|
'raw' => '%s', |
67
|
|
|
]; |
68
|
|
|
|
69
|
|
|
if ('' !== $lineNo = $this->formatLineNo()) { |
70
|
|
|
$lineNo = \sprintf($formats['lineno'], $lineNo); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return $lineNo . \sprintf($formats[$type], $line); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|