@@ -18,6 +18,18 @@ abstract class Pretty
18
18
/** @var string The PHP code. */
19
19
protected $ code ;
20
20
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
+
21
33
/** @var bool Indicates if it has been already configured. */
22
34
protected static $ configured ;
23
35
@@ -48,28 +60,57 @@ public static function configure()
48
60
static ::$ configured = true ;
49
61
}
50
62
63
+ protected function setOptions (array $ options )
64
+ {
65
+ if ($ options ['lineNo ' ] ?? false ) {
66
+ $ this ->withLineNo = true ;
67
+ }
68
+ }
69
+
51
70
protected function parse (string $ code = null )
52
71
{
53
72
$ this ->reset ();
54
73
55
74
$ dom = new \DOMDocument ;
56
- $ dom ->loadHTML ($ this ->codeToHtml ($ code ));
75
+ $ dom ->loadHTML ($ this ->codeToHtml ($ code ?? $ this -> code ));
57
76
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 ;
59
80
$ this ->visit ($ el );
60
81
}
61
82
}
62
83
63
- protected function codeToHtml (string $ code = null ): string
84
+ protected function codeToHtml (string $ code ): string
64
85
{
65
86
static ::configure ();
66
87
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 ();
68
108
69
- return \str_replace (['<br /> ' , '<code> ' , '</code> ' ], ["\n" , '' , '' ], $ html );
109
+ $ this ->lengths = [];
110
+ $ this ->lineNo = $ this ->lineCount = 0 ;
70
111
}
71
112
72
- abstract protected function reset ();
113
+ abstract protected function doReset ();
73
114
74
115
abstract protected function visit (\DOMNode $ el );
75
116
}
0 commit comments