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