$code = <<
namespace Name\Space;
class SomeClass
{
protected function check($orderData)
{
if ($result) {
}
}
}
CODE;
// 1.将php源代码转成ast
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
try {
$ast = $parser->parse($code);
} catch (Error $error) {
echo "Parse error: {$error->getMessage()}\n";
return;
}
$traverser = new NodeTraverser;
// 2. 修改if子句
$traverser->addVisitor(new class extends NodeVisitorAbstract {
public function leaveNode(Node $node) {
if ($node instanceof If_) {
$node->stmts = [
(new BuilderFactory)->var('foo')
];
}
}
});
$traverser->traverse($ast);
// 3. 输出php代码
$prettyPrinter = new PrettyPrinter\Standard();
echo $prettyPrinter->prettyPrintFile($ast);
}
最后生成的代码如下
namespace Name\Space;
class SomeClass
{
protected function check($orderData)
{
if ($result) {
$foo
}
}
}
可以看到$foo变量后面的分号丢掉了...