先说结果,没有成功,已经提了issue:https://github.com/nikic/PHP-Parser/issues/731
代码如下:
$code = <<<'CODE'
<?php
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);
}
最后生成的代码如下
<?php
namespace Name\Space;
class SomeClass
{
protected function check($orderData)
{
if ($result) {
$foo
}
}
}
可以看到$foo变量后面的分号丢掉了...
网友评论