Skip to content

Commit 4662099

Browse files
committed
Factory::extractBody() replaces multi-line & HEREDOC strings with single-line
1 parent 69eebb7 commit 4662099

File tree

2 files changed

+36
-20
lines changed

2 files changed

+36
-20
lines changed

src/PhpGenerator/Factory.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,38 @@ private function extractBody(PhpParser\NodeFinder $nodeFinder, string $originalC
241241
}
242242
}
243243

244+
// multi-line strings => singleline
245+
foreach (array_merge(
246+
$nodeFinder->findInstanceOf($statements, Node\Scalar\String_::class),
247+
$nodeFinder->findInstanceOf($statements, Node\Scalar\EncapsedStringPart::class)
248+
) as $node) {
249+
$token = substr($body, $node->getStartFilePos() - $start, $node->getEndFilePos() - $node->getStartFilePos() + 1);
250+
if (strpos($token, "\n") !== false) {
251+
$quote = $node instanceof Node\Scalar\String_ ? '"' : '';
252+
$replacements[] = [
253+
$node->getStartFilePos(),
254+
$node->getEndFilePos(),
255+
$quote . addcslashes($node->value, "\x00..\x1F") . $quote,
256+
];
257+
}
258+
}
259+
260+
// HEREDOC => "string"
261+
foreach ($nodeFinder->findInstanceOf($statements, Node\Scalar\Encapsed::class) as $node) {
262+
if ($node->getAttribute('kind') === Node\Scalar\String_::KIND_HEREDOC) {
263+
$replacements[] = [
264+
$node->getStartFilePos(),
265+
$node->parts[0]->getStartFilePos() - 1,
266+
'"',
267+
];
268+
$replacements[] = [
269+
end($node->parts)->getEndFilePos() + 1,
270+
$node->getEndFilePos(),
271+
'"',
272+
];
273+
}
274+
}
275+
244276
//sort collected resolved names by position in file
245277
usort($replacements, function ($a, $b) {
246278
return $a[0] <=> $b[0];

tests/PhpGenerator/expected/ClassType.from.bodies.expect

Lines changed: 4 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -58,28 +58,12 @@ abstract class Class7
5858
comment */
5959
// Alias Method will not be resolved in comment
6060
if ($member instanceof \Abc\Method) {
61-
$s1 = '
62-
a
63-
b
64-
c
65-
';
66-
$s2 = "
67-
a
68-
{$b}
69-
$c
70-
";
61+
$s1 = "\na\n\tb\n\t\tc\n";
62+
$s2 = "\na\n\t{$b}\n\t\t$c\n";
7163

72-
$s3 = <<<DOC
73-
a
74-
{$b}
75-
$c
76-
DOC
64+
$s3 = "a\n\t{$b}\n\t\t$c"
7765
;
78-
$s3 = <<<'DOC'
79-
a
80-
b
81-
c
82-
DOC
66+
$s3 = "a\n\tb\n\t\tc"
8367
;
8468
?>
8569
a

0 commit comments

Comments
 (0)