Completed
Push — master ( f06ad0...9cb85d )
by Nico
06:26
created

Highlighter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 57
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setStyle() 0 10 2
A highlightString() 0 4 1
A highlightTokens() 0 15 3
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