1
0
mirror of https://github.com/danog/PHP-Parser.git synced 2024-11-26 20:04:48 +01:00

FPPP: Fix insertion of multiple elems at start

This commit is contained in:
Nikita Popov 2017-12-02 15:10:15 +01:00
parent 04feb90d79
commit 4fcdac40d1
2 changed files with 64 additions and 23 deletions

View File

@ -688,9 +688,8 @@ abstract class PrettyPrinterAbstract
) {
$diff = $this->nodeListDiffer->diffWithReplacements($origNodes, $nodes);
/** @var Node|null $delayedAddNode Used for insertions at the start of the list */
$delayedAddNode = null;
$delayedAddInsertStr = '';
$beforeFirstKeepOrReplace = true;
$delayedAdd = [];
$result = '';
foreach ($diff as $i => $diffElem) {
@ -701,6 +700,8 @@ abstract class PrettyPrinterAbstract
$origArrItem = $diffElem->old;
if ($diffType === DiffElem::TYPE_KEEP || $diffType === DiffElem::TYPE_REPLACE) {
$beforeFirstKeepOrReplace = false;
if ($origArrItem === null || $arrItem === null) {
// We can only handle the case where both are null
if ($origArrItem === $arrItem) {
@ -739,10 +740,12 @@ abstract class PrettyPrinterAbstract
$itemStartPos = $commentStartPos;
}
if (null !== $delayedAddNode) {
if (!empty($delayedAdd)) {
$result .= $this->origTokens->getTokenCode(
$pos, $commentStartPos, $indentAdjustment);
/** @var Node $delayedAddNode */
foreach ($delayedAdd as list($delayedAddNode, $delayedAddInsertStr)) {
if ($delayedAddInsertStr === "\n") {
$delayedAddComments = $delayedAddNode->getComments();
if ($delayedAddComments) {
@ -757,11 +760,12 @@ abstract class PrettyPrinterAbstract
} else {
$result .= $delayedAddInsertStr;
}
}
$result .= $this->origTokens->getTokenCode(
$commentStartPos, $itemStartPos, $indentAdjustment);
$delayedAddNode = null;
$delayedAdd = [];
} else {
$result .= $this->origTokens->getTokenCode(
$pos, $itemStartPos, $indentAdjustment);
@ -777,15 +781,9 @@ abstract class PrettyPrinterAbstract
return null;
}
if ($i === 0) {
if (count($diff) === 1) {
// TODO Handle insertion into empty list
return null;
}
if ($beforeFirstKeepOrReplace) {
// These will be inserted at the next "replace" or "keep" element
$delayedAddNode = $arrItem;
$delayedAddInsertStr = $insertStr;
$delayedAdd[] = [$arrItem, $insertStr];
continue;
}
@ -834,6 +832,12 @@ abstract class PrettyPrinterAbstract
$this->setIndentLevel($origIndentLevel);
$pos = $itemEndPos + 1;
}
if (!empty($delayedAdd)) {
// TODO Handle insertion into empty list
return null;
}
return $result;
}

View File

@ -240,3 +240,40 @@ function test() {
$baz;
$foo; $bar;
}
-----
<?php
function test() {
// Foo bar
$foo; $bar;
}
-----
array_unshift(
$stmts[0]->stmts,
new Stmt\Expression(new Expr\Variable('a')),
new Stmt\Expression(new Expr\Variable('b')));
-----
<?php
function test() {
$a;
$b;
// Foo bar
$foo; $bar;
}
-----
<?php
function test() {}
-----
/* Insertion into empty list not handled yet */
$stmts[0]->stmts = [
new Stmt\Expression(new Expr\Variable('a')),
new Stmt\Expression(new Expr\Variable('b')),
];
-----
<?php
function test()
{
$a;
$b;
}