Passed
Pull Request — master (#1)
by Jitendra
01:28
created

Pretty::codeToHtml()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 3
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 7
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
abstract class Pretty
17
{
18
    /** @var string The PHP code. */
19
    protected $code;
20
21
    /** @var bool Indicates if it has been already configured. */
22
    protected static $configured;
23
24
    public function __construct(string $code = null)
25
    {
26
        $this->code = $code ?? '';
27
    }
28
29
    public static function for(string $file): self
30
    {
31
        if (!\is_file($file)) {
32
            throw new \InvalidArgumentException('The given file doesnot exist or is unreadable.');
33
        }
34
35
        return new static(\file_get_contents($file));
36
    }
37
38
    public static function configure()
39
    {
40
        if (static::$configured) {
41
            return;
42
        }
43
44
        foreach (['comment', 'default', 'html', 'keyword', 'string'] as $type) {
45
            \ini_set("highlight.$type", \ini_get("highlight.$type") . \sprintf('" data-type="%s', $type));
46
        }
47
48
        static::$configured = true;
49
    }
50
51
    protected function parse(string $code = null)
52
    {
53
        $this->reset();
54
55
        $dom = new \DOMDocument;
56
        $dom->loadHTML($this->codeToHtml($code));
57
58
        foreach ((new \DOMXPath($dom))->query('/html/body/span')[0]->childNodes as $el) {
59
            $this->visit($el);
60
        }
61
    }
62
63
    protected function codeToHtml(string $code = null): string
64
    {
65
        static::configure();
66
67
        $html = \highlight_string($code ?? $this->code, true);
68
69
        return \str_replace(['<br />', '<code>', '</code>'], ["\n", '', ''], $html);
70
    }
71
72
    abstract protected function reset();
73
74
    abstract protected function visit(\DOMNode $el);
75
}
76