Skip to content

Commit 7218f4b

Browse files
committed
Fix newline handling in parsed text
This is hacky. It predates a similar approach proposed in #165 and is not the more complete solution proposed in #173, but it'll at least sync the code with that used in production. Fixes #114, see #165, see #173.
1 parent 1bd9179 commit 7218f4b

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

lib/runner.php

+42-1
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,47 @@ function parse_files( $files, $root ) {
133133
return $output;
134134
}
135135

136+
/**
137+
* Fixes newline handling in parsed text.
138+
*
139+
* DocBlock lines, particularly for descriptions, generally adhere to a given character width. For sentences and
140+
* paragraphs that exceed that width, what is intended as a manual soft wrap (via line break) is used to ensure
141+
* on-screen/in-file legibility of that text. These line breaks are retained by phpDocumentor. However, consumers
142+
* of this parsed data may believe the line breaks to be intentional and may display the text as such.
143+
*
144+
* This function fixes text by merging consecutive lines of text into a single line. A special exception is made
145+
* for text appearing in `<code>` and `<pre>` tags, as newlines appearing in those tags are always intentional.
146+
*
147+
* @param string $text
148+
*
149+
* @return string
150+
*/
151+
function fix_newlines( $text ) {
152+
// Non-naturally occurring string to use as temporary replacement.
153+
$replacement_string = '{{{{{}}}}}';
154+
155+
// Replace newline characters within 'code' and 'pre' tags with replacement string.
156+
$text = preg_replace_callback(
157+
"/(?<=<pre><code>)(.+)(?=<\/code><\/pre>)/s",
158+
function ( $matches ) {
159+
return preg_replace( '/[\n\r]/', $replacement_string, $matches[1] );
160+
},
161+
$text
162+
);
163+
164+
// Merge consecutive non-blank lines together by replacing the newlines with a space.
165+
$text = preg_replace(
166+
"/[\n\r](?!\s*[\n\r])/m",
167+
' ',
168+
$text
169+
);
170+
171+
// Restore newline characters into code blocks.
172+
$text = str_replace( $replacement_string, "\n", $text );
173+
174+
return $text;
175+
}
176+
136177
/**
137178
* @param BaseReflector|ReflectionAbstract $element
138179
*
@@ -150,7 +191,7 @@ function export_docblock( $element ) {
150191

151192
$output = array(
152193
'description' => preg_replace( '/[\n\r]+/', ' ', $docblock->getShortDescription() ),
153-
'long_description' => preg_replace( '/[\n\r]+/', ' ', $docblock->getLongDescription()->getFormattedContents() ),
194+
'long_description' => fix_newlines( $docblock->getLongDescription()->getFormattedContents() ),
154195
'tags' => array(),
155196
);
156197

0 commit comments

Comments
 (0)