@@ -29,6 +29,11 @@ class Highlighter
2929 /** @var Style */
3030 private $ color ;
3131
32+ /**
33+ * @var self
34+ */
35+ private static $ instance ;
36+
3237 /** @var array */
3338 private $ defaultTheme = [
3439 self ::TOKEN_STRING => 'red ' ,
@@ -40,6 +45,18 @@ class Highlighter
4045 self ::LINE_NUMBER => 'darkGray ' ,
4146 ];
4247
48+ /**
49+ * @return Highlighter
50+ */
51+ public static function create ()
52+ {
53+ if (!self ::$ instance ) {
54+ self ::$ instance = new self ();
55+ }
56+
57+ return self ::$ instance ;
58+ }
59+
4360 /**
4461 * @param Style $color
4562 */
@@ -50,15 +67,15 @@ public function __construct(Style $color = null)
5067
5168 /**
5269 * @param string $source
53- * @param bool $withLn with line number
70+ * @param bool $withLineNumber with line number
5471 * @return string
5572 */
56- public function highlight (string $ source , $ withLn = false )
73+ public function highlight (string $ source , $ withLineNumber = false )
5774 {
5875 $ tokenLines = $ this ->getHighlightedLines ($ source );
5976 $ lines = $ this ->colorLines ($ tokenLines );
6077
61- if ($ withLn ) {
78+ if ($ withLineNumber ) {
6279 return $ this ->lineNumbers ($ lines );
6380 }
6481
@@ -237,7 +254,6 @@ private function colorLines(array $tokenLines)
237254
238255 foreach ($ tokenLines as $ lineCount => $ tokenLine ) {
239256 $ line = '' ;
240- // foreach ($tokenLine as $token) {
241257 foreach ($ tokenLine as list ($ tokenType , $ tokenValue )) {
242258 $ style = $ this ->defaultTheme [$ tokenType ];
243259
@@ -262,8 +278,9 @@ private function colorLines(array $tokenLines)
262278 private function lineNumbers (array $ lines , $ markLine = null )
263279 {
264280 end ($ lines );
265- $ lineStrlen = \strlen ( key ( $ lines ) + 1 );
281+
266282 $ snippet = '' ;
283+ $ lineLen = \strlen (key ($ lines ) + 1 );
267284 $ lmStyle = $ this ->defaultTheme [self ::ACTUAL_LINE_MARK ];
268285 $ lnStyle = $ this ->defaultTheme [self ::LINE_NUMBER ];
269286
@@ -272,7 +289,7 @@ private function lineNumbers(array $lines, $markLine = null)
272289 $ snippet .= ($ markLine === $ i + 1 ? $ this ->color ->apply ($ lmStyle , ' > ' ) : ' ' );
273290 }
274291
275- $ snippet .= $ this ->color ->apply ($ lnStyle , str_pad ($ i + 1 , $ lineStrlen , ' ' , STR_PAD_LEFT ) . '| ' );
292+ $ snippet .= $ this ->color ->apply ($ lnStyle , str_pad ($ i + 1 , $ lineLen , ' ' , STR_PAD_LEFT ) . '| ' );
276293 $ snippet .= $ line . PHP_EOL ;
277294 }
278295
0 commit comments