@@ -53,43 +53,39 @@ public function __construct(CodeNode $codeNode, TemplateRenderer $templateRender
53
53
54
54
public function render (): string
55
55
{
56
- $ this ->configureHighlighter ();
57
-
58
- $ value = $ this ->codeNode ->getValue ();
59
-
56
+ $ code = $ this ->codeNode ->getValue ();
60
57
if ($ this ->codeNode ->isRaw ()) {
61
- return $ value ;
62
- }
63
-
64
- $ lines = $ this ->getLines ($ value );
65
- $ code = implode ("\n" , $ lines );
66
-
67
- $ lineNumbers = '' ;
68
- for ($ i = 1 ; $ i <= \count ($ lines ); ++$ i ) {
69
- $ lineNumbers .= u ((string ) $ i )->padStart (2 , ' ' )."\n" ;
58
+ return $ code ;
70
59
}
71
60
72
61
$ language = $ this ->codeNode ->getLanguage () ?? 'php ' ;
62
+ $ languageMapping = self ::LANGUAGES_MAPPING [$ language ] ?? $ language ;
63
+ $ languages = array_unique ([$ language , $ languageMapping ]);
64
+
65
+ if ('text ' === $ language ) {
66
+ $ highlightedCode = $ code ;
67
+ } else {
68
+ $ this ->configureHighlighter ();
73
69
74
- if ('text ' !== $ language ) {
75
70
$ highLighter = new Highlighter ();
76
- $ code = $ highLighter ->highlight (self :: LANGUAGES_MAPPING [ $ language ] ?? $ language , $ code )->value ;
71
+ $ highlightedCode = $ highLighter ->highlight ($ languageMapping , $ code )->value ;
77
72
78
73
// this allows to highlight the $ in PHP variable names
79
- $ code = str_replace ('<span class="hljs-variable">$ ' , '<span class="hljs-variable"><span class="hljs-variable-other-marker">$</span> ' , $ code );
74
+ $ highlightedCode = str_replace ('<span class="hljs-variable">$ ' , '<span class="hljs-variable"><span class="hljs-variable-other-marker">$</span> ' , $ highlightedCode );
80
75
}
81
76
77
+ $ numOfLines = \count (preg_split ('/\r\n|\r|\n/ ' , $ highlightedCode ));
78
+
82
79
return $ this ->templateRenderer ->render (
83
80
'code.html.twig ' ,
84
81
[
85
- 'language ' => $ language ,
86
- 'languageMapping ' => self ::LANGUAGES_MAPPING [$ language ] ?? $ language ,
87
- 'code ' => $ code ,
88
- 'lineNumbers ' => rtrim ($ lineNumbers ),
82
+ 'languages ' => $ languages ,
83
+ 'lines ' => range (1 , $ numOfLines - 1 ),
84
+ 'code ' => $ highlightedCode ,
89
85
// this is the number of digits of the codeblock lines-of-code
90
86
// e.g. LOC = 5, digits = 1; LOC = 18, digits = 2
91
87
// this is useful to tweak the code listings according to their length
92
- 'numLocDigits ' => strlen ((string ) \count ( $ lines ) ),
88
+ 'numLocDigits ' => strlen ((string ) $ numOfLines ),
93
89
]
94
90
);
95
91
}
0 commit comments