php - 如何遍历具有If条件的PHP源代码
问题描述
我正在使用PHP-Parser来评估用于遍历 if 语句的条件。我只想知道在代码的遍历过程中使用了哪些条件。例如:
测试
<?php
$val = true;
if ($val == true){
$result = true;
} else {
$result = false;
}
我已经找到了测试代码的AST,如下
AST
array( 0: Stmt_Expression( expr: Expr_Assign( var: Expr_Variable( name: val ) expr: Expr_ConstFetch( name: Name( parts: array( 0: true ) ) ) ) ) 1: Stmt_If( cond: Expr_BinaryOp_Equal( left: Expr_Variable( name: val ) right: Expr_ConstFetch( name: Name( parts: array( 0: true ) ) ) ) stmts: array( 0: Stmt_Expression( expr: Expr_Assign( var: Expr_Variable( name: result ) expr: Expr_ConstFetch( name: Name( parts: array( 0: true ) ) ) ) ) ) elseifs: array( ) else: Stmt_Else( stmts: array( 0: Stmt_Expression( expr: Expr_Assign( var: Expr_Variable( name: result ) expr: Expr_ConstFetch( name: Name( parts: array( 0: false ) ) ) ) ) ) ) ) )
我想要得到的是遍历期间测试代码中使用的条件,预计是这样的:
预期结果
Conditions: (operator: Equal true:bool,true:bool,)
// OR
Condition: (operator: NOT (operator: Equal true:bool,true:bool,),)
所以我只是想知道如何获得遍历过程中通过的条件。
解决方案
我要说的一件事是你不一定能得到两个运算符的值,因为这是在运行时完成的而不是解析的。所以而不是
Conditions: (operator: Equal true:bool,true:bool,)
你可以得到类似...
Conditions: (operator: Equal left -> $val, right -> true,)
这是基于上一个问题/答案的内容如何使用 PHP-Parser 获取全局变量名称并更改它。
所以目前的代码是......
$code = <<<'CODE'
<?php
$val = true;
if ($val == true){
$result = true;
} else {
$result = false;
}
CODE;
$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;
$traverser->addVisitor(new class extends NodeVisitorAbstract {
public function leaveNode(Node $node){
if ($node instanceof PhpParser\Node\Stmt\If_ ) {
$prettyPrinter = new PhpParser\PrettyPrinter\Standard;
echo "left=".$prettyPrinter->prettyPrintExpr($node->cond->left).
" ".get_class($node->cond).
" right=".$prettyPrinter->prettyPrintExpr($node->cond->right).PHP_EOL;
echo "expression is `".$prettyPrinter->prettyPrintExpr($node->cond)."`".PHP_EOL;
}
}
});
$traverser->traverse($ast);
这会给...
left=$val PhpParser\Node\Expr\BinaryOp\Equal right=true
expression is `$val == true`
推荐阅读
- python - 在数据框中分隔 2 个数组
- python - 安装的 OpenCV 无法在 PyCharms Python 3.8 项目上运行
- postgresql - 如何使用 postgresql 角色连接数据库?
- python - 如何使用 cmd 运行用 Spider 编写的 python 程序
- windows - 如何从命令行在目标字段中执行带有空格的快捷方式?
- javascript - 在 NodeJS 中循环后获取新数组值时遇到问题
- angular - Angular 8 Resolver 不工作:没有 Resolver 的提供者
- javascript - 循环对象数组返回一个数组
- sql-server - 如何正确截断 ETL 管道中的临时表?
- angularjs - 如何在 ng-repeat 中访问子范围