Print comments of inserted statements

This commit is contained in:
Nikita Popov 2017-10-06 17:58:56 +02:00
parent 57bc42517b
commit f071b66013
3 changed files with 38 additions and 1 deletions

View File

@ -717,7 +717,14 @@ abstract class PrettyPrinterAbstract
if ($insertStr === "\n") {
// TODO Try to deduplicate this code
$indentLevel = $this->origTokens->getIndentationBefore($itemStartPos) + $indentAdjustment;
$result .= $insertStr . str_repeat(' ', $indentLevel);
$comments = $arrItem->getComments();
if ($comments) {
// TODO pComment here uses the wrong indentation level.
// The FP/non-FP indentation levels need to be merged, to reduce this mess...
$result .= "\n" . str_repeat(' ', $indentLevel) . $this->pComments($comments);
}
$result .= "\n" . str_repeat(' ', $indentLevel);
} else {
$result .= $insertStr;
}

View File

@ -234,6 +234,7 @@ class PrettyPrinterTest extends CodeTestAbstract
/** @var callable $fn */
eval(<<<CODE
use PhpParser\Comment;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Scalar;

View File

@ -99,4 +99,33 @@ $stmts[0]->catches[] = new Stmt\Catch_([new Node\Name('Bar')], new Expr\Variable
try {
} catch (Foo $foo) {
} catch (Bar $bar) {
}
-----
<?php
$foo; $bar;
-----
$node = new Stmt\Expression(new Expr\Variable('baz'));
$node->setAttribute('comments', [new Comment('// Test')]);
$stmts[] = $node;
-----
<?php
$foo; $bar;
// Test
$baz;
-----
<?php
function test() {
$foo; $bar;
}
-----
$node = new Stmt\Expression(new Expr\Variable('baz'));
$node->setAttribute('comments', [new Comment('// Test'), new Comment('// Test 2')]);
$stmts[0]->stmts[] = $node;
-----
<?php
function test() {
$foo; $bar;
// Test
// Test 2
$baz;
}