1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @license http://opensource.org/licenses/mit-license.php MIT |
5
|
|
|
* @link https://github.com/nicoSWD |
6
|
|
|
* @author Nicolas Oelgart <[email protected]> |
7
|
|
|
*/ |
8
|
|
|
namespace nicoSWD\Rule\Highlighter; |
9
|
|
|
|
10
|
|
|
use ArrayIterator; |
11
|
|
|
use nicoSWD\Rule\Tokenizer\TokenizerInterface; |
12
|
|
|
use nicoSWD\Rule\TokenStream\Token\BaseToken; |
13
|
|
|
use nicoSWD\Rule\TokenStream\Token\TokenType; |
14
|
|
|
use SplObjectStorage; |
15
|
|
|
|
16
|
|
|
final class Highlighter |
17
|
|
|
{ |
18
|
|
|
private readonly SplObjectStorage $styles; |
|
|
|
|
19
|
|
|
|
20
|
|
|
public function __construct( |
21
|
|
|
private readonly TokenizerInterface $tokenizer, |
22
|
|
|
) { |
23
|
|
|
$this->styles = $this->defaultStyles(); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function setStyle(TokenType $group, string $style): void |
27
|
|
|
{ |
28
|
|
|
$this->styles[$group] = $style; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function highlightString(string $string): string |
32
|
|
|
{ |
33
|
|
|
return $this->highlightTokens($this->tokenizer->tokenize($string)); |
34
|
|
|
} |
35
|
|
|
|
36
|
4 |
|
public function highlightTokens(ArrayIterator $tokens): string |
37
|
|
|
{ |
38
|
4 |
|
$string = ''; |
39
|
4 |
|
|
40
|
|
|
foreach ($tokens as $token) { |
41
|
4 |
|
/** @var BaseToken $token */ |
42
|
|
|
$tokenType = $token->getType(); |
43
|
4 |
|
|
44
|
2 |
|
if (isset($this->styles[$tokenType])) { |
45
|
2 |
|
$string .= '<span style="' . $this->styles[$tokenType] . '">' . $this->encode($token) . '</span>'; |
46
|
|
|
} else { |
47
|
|
|
$string .= $token->getOriginalValue(); |
48
|
|
|
} |
49
|
2 |
|
} |
50
|
2 |
|
|
51
|
|
|
return '<pre><code>' . $string . '</code></pre>'; |
52
|
2 |
|
} |
53
|
|
|
|
54
|
2 |
|
private function encode(BaseToken $token): string |
55
|
|
|
{ |
56
|
|
|
return htmlentities($token->getOriginalValue(), ENT_QUOTES, 'utf-8'); |
57
|
2 |
|
} |
58
|
|
|
|
59
|
2 |
|
private function defaultStyles(): SplObjectStorage |
60
|
|
|
{ |
61
|
2 |
|
$styles = new SplObjectStorage(); |
62
|
2 |
|
$styles[TokenType::COMMENT] = 'color: #948a8a; font-style: italic;'; |
63
|
2 |
|
$styles[TokenType::LOGICAL] = 'color: #c72d2d;'; |
64
|
2 |
|
$styles[TokenType::OPERATOR] = 'color: #000;'; |
65
|
|
|
$styles[TokenType::PARENTHESIS] = 'color: #000;'; |
66
|
2 |
|
$styles[TokenType::VALUE] = 'color: #e36700; font-style: italic;'; |
67
|
|
|
$styles[TokenType::VARIABLE] = 'color: #007694; font-weight: 900;'; |
68
|
|
|
$styles[TokenType::METHOD] = 'color: #000'; |
69
|
|
|
|
70
|
2 |
|
return $styles; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|