Highlighter   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 5
Bugs 0 Features 2
Metric Value
eloc 26
c 5
b 0
f 2
dl 0
loc 58
rs 10
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __toString() 0 3 1
A highlight() 0 7 1
A doReset() 0 3 1
A visit() 0 15 4
A formatLine() 0 16 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the CLI-SYNTAX package.
7
 *
8
 * (c) Jitendra Adhikari <[email protected]>
9
 *     <https://github.com/adhocore>
10
 *
11
 * Licensed under MIT license.
12
 */
13
14
namespace Ahc\CliSyntax;
15
16
class Highlighter extends Pretty
17
{
18
    /** @var string Output string */
19
    protected $out = '';
20
21
    public function __toString(): string
22
    {
23
        return $this->highlight();
24
    }
25
26
    public function highlight(string $code = null, array $options = []): string
27
    {
28
        $this->setOptions($options);
29
30
        $this->parse($code ?? $this->code);
31
32
        return \trim($this->out, "\n") . "\n";
33
    }
34
35
    protected function doReset()
36
    {
37
        $this->out = '';
38
    }
39
40
    protected function visit(\DOMNode $el)
41
    {
42
        $type = $el instanceof \DOMElement ? $el->getAttribute('data-type') : 'raw';
43
        $text = \str_replace(['&nbsp;', '&lt;', '&gt;'], [' ', '<', '>'], $el->textContent);
44
45
        $lastLine = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $lastLine is dead and can be removed.
Loading history...
46
        $lines    = \explode("\n", $text);
47
        foreach ($lines as $i => $line) {
48
            $this->out .= $this->formatLine($type, $line);
49
50
            if (isset($lines[$i + 1])) {
51
                $this->out .= "\n";
52
            }
53
54
            $this->lengths[$this->lineNo++] = \strlen($line);
55
        }
56
    }
57
58
    protected function formatLine(string $type, string $line)
59
    {
60
        static $formats = [
61
            'comment' => "\033[0;34;40m%s\033[0m",
62
            'default' => "\033[0;32;40m%s\033[0m",
63
            'keyword' => "\033[0;31;40m%s\033[0m",
64
            'string'  => "\033[0;33;40m%s\033[0m",
65
            'lineno'  => "\033[2;36;40m%s\033[0m",
66
            'raw'     => '%s',
67
        ];
68
69
        if ('' !== $lineNo = $this->formatLineNo()) {
70
            $lineNo = \sprintf($formats['lineno'], $lineNo);
71
        }
72
73
        return $lineNo . \sprintf($formats[$type], $line);
74
    }
75
}
76