Passed
Pull Request — master (#1)
by Jitendra
02:41
created

Highlighter::visit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 2
Metric Value
cc 2
eloc 8
c 3
b 0
f 2
nc 2
nop 1
dl 0
loc 13
rs 10
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): string
27
    {
28
        $this->parse($code);
29
30
        return \trim($this->out, "\n") . "\n";
31
    }
32
33
    protected function reset()
34
    {
35
        $this->out = '';
36
    }
37
38
    protected function visit(\DOMNode $el)
39
    {
40
        static $formats = [
41
            'comment' => "\033[0;34;40m%s\033[0m",
42
            'default' => "\033[0;32;40m%s\033[0m",
43
            'keyword' => "\033[0;31;40m%s\033[0m",
44
            'string'  => "\033[0;33;40m%s\033[0m",
45
        ];
46
47
        $type = $el instanceof \DOMElement ? $el->getAttribute('data-type') : 'raw';
48
        $text = \str_replace(['&nbsp;', '&lt;', '&gt;'], [' ', '<', '>'], $el->textContent);
49
50
        $this->out .= \sprintf($formats[$type] ?? '%s', $text);
51
    }
52
}
53