diff --git a/lib/PhpParser/PrettyPrinterAbstract.php b/lib/PhpParser/PrettyPrinterAbstract.php index 5fc3653..70873ae 100644 --- a/lib/PhpParser/PrettyPrinterAbstract.php +++ b/lib/PhpParser/PrettyPrinterAbstract.php @@ -824,7 +824,11 @@ abstract class PrettyPrinterAbstract return null; } - if ($insertStr === ', ' && $this->isMultiline($origNodes)) { + // We go multiline if the original code was multiline, + // or if it's an array item with a comment above it. + if ($insertStr === ', ' && ( + $this->isMultiline($origNodes) || !empty($arrItem->getAttribute('comments'))) + ) { $insertStr = ','; $insertNewline = true; } @@ -842,11 +846,11 @@ abstract class PrettyPrinterAbstract $this->setIndentLevel($lastElemIndentLevel); if ($insertNewline) { + $result .= $insertStr . $this->nl; $comments = $arrItem->getComments(); if ($comments) { - $result .= $this->nl . $this->pComments($comments); + $result .= $this->pComments($comments) . $this->nl; } - $result .= $insertStr . $this->nl; } else { $result .= $insertStr; } diff --git a/test/code/formatPreservation/arrayInsertionWithComments.test b/test/code/formatPreservation/arrayInsertionWithComments.test new file mode 100644 index 0000000..adde626 --- /dev/null +++ b/test/code/formatPreservation/arrayInsertionWithComments.test @@ -0,0 +1,106 @@ +Inserting array item with comment +----- + 'foo', + 'b' => 'bar', +]; +----- +$node = new Expr\ArrayItem(new Scalar\String_('baz'), new Scalar\String_('c')); +$node->setAttribute('comments', [new Comment\Doc(<<expr->expr; +$array->items[] = $node; +----- + 'foo', + 'b' => 'bar', + /** + * A doc comment + */ + 'c' => 'baz', +]; +----- + 'foo', + 'b' => 'bar', +]; +----- +$node = new Expr\ArrayItem(new Scalar\String_('baz'), new Scalar\String_('c')); +$node->setAttribute('comments', [new Comment("/* Block comment */")]); +$array = $stmts[0]->expr->expr; +$array->items[] = $node; +----- + 'foo', + 'b' => 'bar', + /* Block comment */ + 'c' => 'baz', +]; +----- + 'foo', + 'b' => 'bar', +]; +----- +$node = new Expr\ArrayItem(new Scalar\String_('baz'), new Scalar\String_('c')); +$node->setAttribute('comments', [new Comment("// Line comment")]); +$array = $stmts[0]->expr->expr; +$array->items[] = $node; +----- + 'foo', + 'b' => 'bar', + // Line comment + 'c' => 'baz', +]; +----- + 'foo', +]; +----- +$node = new Expr\ArrayItem(new Scalar\String_('bar'), new Scalar\String_('b')); +$node->setAttribute('comments', [new Comment("// Line comment")]); +$array = $stmts[0]->expr->expr; +$array->items[] = $node; +----- + 'foo', + // Line comment + 'b' => 'bar', +]; +----- +setAttribute('comments', [new Comment("// Line comment")]); +$array = $stmts[0]->expr->expr; +$array->items[] = $node; +----- + 'foo', +]; \ No newline at end of file