Skip to content

Commit 513095a

Browse files
committed
feat(pretty): support line no, refactor reset()
1 parent 7377048 commit 513095a

File tree

1 file changed

+47
-6
lines changed

1 file changed

+47
-6
lines changed

src/Pretty.php

+47-6
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,18 @@ abstract class Pretty
1818
/** @var string The PHP code. */
1919
protected $code;
2020

21+
/** @var int The current line number. */
22+
protected $lineNo = 0;
23+
24+
/** @var int The total lines count. */
25+
protected $lineCount = 0;
26+
27+
/** @var bool Show line numbers. */
28+
protected $withLineNo = false;
29+
30+
/** @var array Lengths of each line */
31+
protected $lengths = [];
32+
2133
/** @var bool Indicates if it has been already configured. */
2234
protected static $configured;
2335

@@ -48,28 +60,57 @@ public static function configure()
4860
static::$configured = true;
4961
}
5062

63+
protected function setOptions(array $options)
64+
{
65+
if ($options['lineNo'] ?? false) {
66+
$this->withLineNo = true;
67+
}
68+
}
69+
5170
protected function parse(string $code = null)
5271
{
5372
$this->reset();
5473

5574
$dom = new \DOMDocument;
56-
$dom->loadHTML($this->codeToHtml($code));
75+
$dom->loadHTML($this->codeToHtml($code ?? $this->code));
5776

58-
foreach ((new \DOMXPath($dom))->query('/html/body/span')[0]->childNodes as $el) {
77+
$adjust = -1;
78+
foreach ((new \DOMXPath($dom))->query('/html/body/code/span/*') as $el) {
79+
$this->lineNo = $el->getLineNo() + $adjust;
5980
$this->visit($el);
6081
}
6182
}
6283

63-
protected function codeToHtml(string $code = null): string
84+
protected function codeToHtml(string $code): string
6485
{
6586
static::configure();
6687

67-
$html = \highlight_string($code ?? $this->code, true);
88+
$this->lineCount = \substr_count($code, "\n") ?: 1;
89+
90+
$html = \highlight_string($code, true);
91+
92+
return \str_replace(['<br />'], ["\n"], $html);
93+
return \str_replace(['<br />', '<code>', "\n</code>"], ["\n", '', ''], $html);
94+
}
95+
96+
protected function formatLineNo(): string
97+
{
98+
if ($this->withLineNo && $this->lineNo <= $this->lineCount && !isset($this->lengths[$this->lineNo])) {
99+
return \str_pad("$this->lineNo", \strlen("$this->lineCount"), ' ', \STR_PAD_LEFT) . '. ';
100+
}
101+
102+
return '';
103+
}
104+
105+
protected function reset()
106+
{
107+
$this->doReset();
68108

69-
return \str_replace(['<br />', '<code>', '</code>'], ["\n", '', ''], $html);
109+
$this->lengths = [];
110+
$this->lineNo = $this->lineCount = 0;
70111
}
71112

72-
abstract protected function reset();
113+
abstract protected function doReset();
73114

74115
abstract protected function visit(\DOMNode $el);
75116
}

0 commit comments

Comments
 (0)