Print comma before comments for new array item (#805)

Print comma before rather than after comments. Also switch to multiline mode if inserting an item with comments.

Fixes #804.
This commit is contained in:
Shalvah 2021-09-12 20:51:25 +01:00 committed by GitHub
parent 13549aa794
commit 632ead3a82
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 113 additions and 3 deletions

View File

@ -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;
}

View File

@ -0,0 +1,106 @@
Inserting array item with comment
-----
<?php
$items = [
'a' => 'foo',
'b' => 'bar',
];
-----
$node = new Expr\ArrayItem(new Scalar\String_('baz'), new Scalar\String_('c'));
$node->setAttribute('comments', [new Comment\Doc(<<<COMMENT
/**
* A doc comment
*/
COMMENT
)]);
$array = $stmts[0]->expr->expr;
$array->items[] = $node;
-----
<?php
$items = [
'a' => 'foo',
'b' => 'bar',
/**
* A doc comment
*/
'c' => 'baz',
];
-----
<?php
$items = [
'a' => '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;
-----
<?php
$items = [
'a' => 'foo',
'b' => 'bar',
/* Block comment */
'c' => 'baz',
];
-----
<?php
$items = [
'a' => '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;
-----
<?php
$items = [
'a' => 'foo',
'b' => 'bar',
// Line comment
'c' => 'baz',
];
-----
<?php
$items = [
'a' => '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;
-----
<?php
$items = [
'a' => 'foo',
// Line comment
'b' => 'bar',
];
-----
<?php
$items = [];
-----
$node = new Expr\ArrayItem(new Scalar\String_('foo'), new Scalar\String_('a'));
$node->setAttribute('comments', [new Comment("// Line comment")]);
$array = $stmts[0]->expr->expr;
$array->items[] = $node;
-----
<?php
$items = [
// Line comment
'a' => 'foo',
];