如何遍历具有If条件的PHP源代码

如何遍历具有If条件的PHP源代码,php,debugging,php-parser,Php,Debugging,Php Parser,我使用来评估用于遍历if语句的条件。我只是想知道在遍历代码的过程中使用了什么条件。例如: 试验 我试图得到的是遍历过程中测试代码中使用的条件,预期如下: 预期结果 Conditions: (operator: Equal true:bool,true:bool,) // OR Condition: (operator: NOT (operator: Equal true:bool,true:bool,),) 因此,我只是想知道如何获得遍历过程中传递的条件。我要说的一件事是,您不一定能够获

我使用来评估用于遍历if语句的条件。我只是想知道在遍历代码的过程中使用了什么条件。例如:

试验

我试图得到的是遍历过程中测试代码中使用的条件,预期如下:

预期结果

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,)
这是基于上一个问题/答案

所以现在的代码是

$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);

看到预期的结果,这是我试图从上面的例子中得到的结果,非常有帮助,谢谢
Conditions: (operator: Equal left -> $val, right -> true,)
$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`