首页 > 解决方案 > 如何遍历具有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,),)

所以我只是想知道如何获得遍历过程中通过的条件。

标签: phpdebuggingphp-parser

解决方案


我要说的一件事是你不一定能得到两个运算符的值,因为这是在运行时完成的而不是解析的。所以而不是

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`

推荐阅读