Skip to content

Commit 8c360e2

Browse files
committed
Insert parentheses when adding argument to new
Fixes the issue reported in #1134.
1 parent dca41cd commit 8c360e2

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

lib/PhpParser/PrettyPrinterAbstract.php

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1006,9 +1006,25 @@ protected function pArray(
10061006

10071007
list($findToken, $extraLeft, $extraRight) = $this->emptyListInsertionMap[$mapKey];
10081008
if (null !== $findToken) {
1009-
$insertPos = $this->origTokens->findRight($pos, $findToken) + 1;
1010-
$result .= $this->origTokens->getTokenCode($pos, $insertPos, $indentAdjustment);
1011-
$pos = $insertPos;
1009+
// For anon classes skip to the class keyword.
1010+
$isAnonClassArgs = $mapKey === PrintableNewAnonClassNode::class . '->args';
1011+
if ($isAnonClassArgs) {
1012+
$insertPos = $this->origTokens->findRight($pos, \T_CLASS) + 1;
1013+
$result .= $this->origTokens->getTokenCode($pos, $insertPos, $indentAdjustment);
1014+
$pos = $insertPos;
1015+
}
1016+
1017+
// If "new Foo" was used without arguments, we need to convert to "new Foo()".
1018+
if (($mapKey === Expr\New_::class . '->args' || $isAnonClassArgs) &&
1019+
!$this->origTokens->haveTokenImmediatelyAfter($pos - 1, '(')
1020+
) {
1021+
$extraLeft = '(';
1022+
$extraRight = ')';
1023+
} else {
1024+
$insertPos = $this->origTokens->findRight($pos, $findToken) + 1;
1025+
$result .= $this->origTokens->getTokenCode($pos, $insertPos, $indentAdjustment);
1026+
$pos = $insertPos;
1027+
}
10121028
}
10131029

10141030
$first = true;

test/code/formatPreservation/emptyListInsertion.test

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,29 @@ Foo
108108
new class
109109
($a, $b)
110110
extends Foo {};
111+
-----
112+
<?php
113+
new Foo;
114+
new Foo ;
115+
new Foo();
116+
new Foo ();
117+
new class {};
118+
new class() {};
119+
new class () {};
120+
-----
121+
$stmts[0]->expr->args[] = new Node\Expr\Variable('a');
122+
$stmts[1]->expr->args[] = new Node\Expr\Variable('a');
123+
$stmts[2]->expr->args[] = new Node\Expr\Variable('a');
124+
$stmts[3]->expr->args[] = new Node\Expr\Variable('a');
125+
$stmts[4]->expr->args[] = new Node\Expr\Variable('a');
126+
$stmts[5]->expr->args[] = new Node\Expr\Variable('a');
127+
$stmts[6]->expr->args[] = new Node\Expr\Variable('a');
128+
-----
129+
<?php
130+
new Foo($a);
131+
new Foo($a) ;
132+
new Foo($a);
133+
new Foo ($a);
134+
new class($a) {};
135+
new class($a) {};
136+
new class ($a) {};

0 commit comments

Comments
 (0)