Completed
Push — master ( 737704...b39c01 )
by Jitendra
12s queued 11s
created

Highlighter::formatLine()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 10
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 16
rs 9.9332
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