function Printer::printNodeFormatPreserving
1 call to Printer::printNodeFormatPreserving()
- Printer::printArrayFormatPreserving in vendor/
phpstan/ phpdoc-parser/ src/ Printer/ Printer.php - *
File
-
vendor/
phpstan/ phpdoc-parser/ src/ Printer/ Printer.php, line 764
Class
Namespace
PHPStan\PhpDocParser\PrinterCode
private function printNodeFormatPreserving(Node $node, TokenIterator $originalTokens) : string {
/** @var Node|null $originalNode */
$originalNode = $node->getAttribute(Attribute::ORIGINAL_NODE);
if ($originalNode === null) {
return $this->print($node);
}
$class = get_class($node);
if ($class !== get_class($originalNode)) {
throw new LogicException();
}
$startPos = $originalNode->getAttribute(Attribute::START_INDEX);
$endPos = $originalNode->getAttribute(Attribute::END_INDEX);
if ($startPos < 0 || $endPos < 0) {
throw new LogicException();
}
$result = '';
$pos = $startPos;
$subNodeNames = array_keys(get_object_vars($node));
foreach ($subNodeNames as $subNodeName) {
$subNode = $node->{$subNodeName};
$origSubNode = $originalNode->{$subNodeName};
if (!$subNode instanceof Node && $subNode !== null || !$origSubNode instanceof Node && $origSubNode !== null) {
if ($subNode === $origSubNode) {
// Unchanged, can reuse old code
continue;
}
if (is_array($subNode) && is_array($origSubNode)) {
// Array subnode changed, we might be able to reconstruct it
$listResult = $this->printArrayFormatPreserving($subNode, $origSubNode, $originalTokens, $pos, $class, $subNodeName);
if ($listResult === null) {
return $this->print($node);
}
$result .= $listResult;
continue;
}
return $this->print($node);
}
if ($origSubNode === null) {
if ($subNode === null) {
// Both null, nothing to do
continue;
}
return $this->print($node);
}
$subStartPos = $origSubNode->getAttribute(Attribute::START_INDEX);
$subEndPos = $origSubNode->getAttribute(Attribute::END_INDEX);
if ($subStartPos < 0 || $subEndPos < 0) {
throw new LogicException();
}
if ($subEndPos < $subStartPos) {
return $this->print($node);
}
if ($subNode === null) {
return $this->print($node);
}
$result .= $originalTokens->getContentBetween($pos, $subStartPos);
$mapKey = get_class($node) . '->' . $subNodeName;
$parenthesesNeeded = isset($this->parenthesesMap[$mapKey]) && in_array(get_class($subNode), $this->parenthesesMap[$mapKey], true);
if ($subNode->getAttribute(Attribute::ORIGINAL_NODE) !== null) {
$parenthesesNeeded = $parenthesesNeeded && !in_array(get_class($subNode->getAttribute(Attribute::ORIGINAL_NODE)), $this->parenthesesMap[$mapKey], true);
}
$addParentheses = $parenthesesNeeded && !$originalTokens->hasParentheses($subStartPos, $subEndPos);
if ($addParentheses) {
$result .= '(';
}
$result .= $this->printNodeFormatPreserving($subNode, $originalTokens);
if ($addParentheses) {
$result .= ')';
}
$pos = $subEndPos + 1;
}
return $result . $originalTokens->getContentBetween($pos, $endPos + 1);
}