@@ -57,12 +57,15 @@ public function render(): string
57
57
return $ code ;
58
58
}
59
59
60
+ $ savedCode = $ code ;
61
+
60
62
$ language = $ this ->codeNode ->getLanguage () ?? 'php ' ;
61
63
$ languageMapping = self ::LANGUAGES_MAPPING [$ language ] ?? $ language ;
62
64
$ languages = array_unique ([$ language , $ languageMapping ]);
63
65
64
66
if ('text ' === $ language ) {
65
- $ highlightedCode = $ code ;
67
+ // Highlighter escapes correctly the code, we need to manually escape only for "text" code
68
+ $ highlightedCode = $ this ->escapeForbiddenCharactersInsideCodeBlock ($ code );
66
69
} else {
67
70
$ this ->configureHighlighter ();
68
71
@@ -117,23 +120,6 @@ public static function isLanguageSupported(string $lang): bool
117
120
return \in_array ($ lang , $ supportedLanguages , true );
118
121
}
119
122
120
- private function getLines (string $ code ): array
121
- {
122
- $ lines = preg_split ('/\r\n|\r|\n/ ' , $ code );
123
- $ reversedLines = array_reverse ($ lines );
124
-
125
- // trim empty lines at the end of the code
126
- foreach ($ reversedLines as $ key => $ line ) {
127
- if ('' !== trim ($ line )) {
128
- break ;
129
- }
130
-
131
- unset($ reversedLines [$ key ]);
132
- }
133
-
134
- return array_reverse ($ reversedLines );
135
- }
136
-
137
123
private function configureHighlighter ()
138
124
{
139
125
if (false === self ::$ isHighlighterConfigured ) {
@@ -143,4 +129,15 @@ private function configureHighlighter()
143
129
144
130
self ::$ isHighlighterConfigured = true ;
145
131
}
132
+
133
+ /**
134
+ * Code blocks are displayed in "<pre>" tags, which has some reserved characters:
135
+ * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
136
+ */
137
+ private function escapeForbiddenCharactersInsideCodeBlock (string $ code ): string
138
+ {
139
+ $ codeEscaped = preg_replace ('/&(?!amp;|lt;|gt;|quot;)/ ' , '& ' , $ code );
140
+
141
+ return strtr ($ codeEscaped , ['< ' => '< ' , '> ' => '> ' , '" ' => '" ' ]);
142
+ }
146
143
}
0 commit comments