Passed
Pull Request — master (#22)
by Nico
18:37 queued 03:42
created

Highlighter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 28
dl 0
loc 53
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0
wmc 7
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;
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting T_VARIABLE on line 18 at column 21
Loading history...
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