For automated refactoring where you want to modify only specific parts of the code while leaving the rest of the formatting untouched, use the printFormatPreserving method. This mode attempts to preserve the formatting of AST nodes that have not changed.
To use this functionality, you must follow a specific workflow:
- Parse the original code to get statements and tokens.
- Use a
CloningVisitor to create a copy of the AST before making any modifications. - Modify the cloned AST.
- Call
printFormatPreserving using the new statements, the original statements, and the original tokens.
Warning: If using name resolution, you should likely disable the replaceNodes option to prevent resolved names from being written directly into the AST, which can cause unintended changes in the output.
use PhpParser\{NodeTraverser, NodeVisitor, ParserFactory, PrettyPrinter};
$parser = (new ParserFactory())->createForHostVersion();
$oldStmts = $parser->parse($code);
$oldTokens = $parser->getTokens();
// Run CloningVisitor before making changes to the AST.
$traverser = new NodeTraverser(new NodeVisitor\CloningVisitor());
$newStmts = $traverser->traverse($oldStmts);
// MODIFY $newStmts HERE
$printer = new PrettyPrinter\Standard();
$newCode = $printer->printFormatPreserving($newStmts, $oldStmts, $oldTokens);