|
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 = new SplObjectStorage(); |
|
24
|
|
|
$this->styles[TokenType::COMMENT] = 'color: #948a8a; font-style: italic;'; |
|
25
|
|
|
$this->styles[TokenType::LOGICAL] = 'color: #c72d2d;'; |
|
26
|
|
|
$this->styles[TokenType::OPERATOR] = 'color: #000;'; |
|
27
|
|
|
$this->styles[TokenType::PARENTHESIS] = 'color: #000;'; |
|
28
|
|
|
$this->styles[TokenType::VALUE] = 'color: #e36700; font-style: italic;'; |
|
29
|
|
|
$this->styles[TokenType::VARIABLE] = 'color: #007694; font-weight: 900;'; |
|
30
|
|
|
$this->styles[TokenType::METHOD] = 'color: #000'; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function setStyle(TokenType $group, string $style): void |
|
34
|
|
|
{ |
|
35
|
|
|
$this->styles[$group] = $style; |
|
36
|
4 |
|
} |
|
37
|
|
|
|
|
38
|
4 |
|
public function highlightString(string $string): string |
|
39
|
4 |
|
{ |
|
40
|
|
|
return $this->highlightTokens($this->tokenizer->tokenize($string)); |
|
41
|
4 |
|
} |
|
42
|
|
|
|
|
43
|
4 |
|
public function highlightTokens(ArrayIterator $tokens): string |
|
44
|
2 |
|
{ |
|
45
|
2 |
|
$string = ''; |
|
46
|
|
|
|
|
47
|
|
|
foreach ($tokens as $token) { |
|
48
|
|
|
/** @var BaseToken $token */ |
|
49
|
2 |
|
$tokenType = $token->getType(); |
|
50
|
2 |
|
|
|
51
|
|
|
if (isset($this->styles[$tokenType])) { |
|
52
|
2 |
|
$string .= '<span style="' . $this->styles[$tokenType] . '">' . $this->encode($token) . '</span>'; |
|
53
|
|
|
} else { |
|
54
|
2 |
|
$string .= $token->getOriginalValue(); |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
2 |
|
|
|
58
|
|
|
return '<pre><code>' . $string . '</code></pre>'; |
|
59
|
2 |
|
} |
|
60
|
|
|
|
|
61
|
2 |
|
private function encode(BaseToken $token): string |
|
62
|
2 |
|
{ |
|
63
|
2 |
|
return htmlentities($token->getOriginalValue(), ENT_QUOTES, 'utf-8'); |
|
64
|
2 |
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|