0

I'm using PHP-Parser to evaluate the conditions used to traverse the if statement. I just want to know what the conditions used during the traversing of the code. For example:

test

<?php 
$val = true;
if ($val == true){
   $result = true;
} else {
   $result  = false;
}

I already found the AST of the test code, which is as following

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

What I'm trying to get is what the condition used in the test code during the traverse, which is expect to be something like this:

Expected result

Conditions: (operator: Equal true:bool,true:bool,)

// OR 

Condition: (operator: NOT (operator: Equal true:bool,true:bool,),)

So I'm just wondering how to get the conditions that passing during the traverse.

1 Answers1

1

The one thing I will say is that you can not necessarily get the values of both operators, as this is something that is done at runtime and not parsing. So instead of

Conditions: (operator: Equal true:bool,true:bool,)

You could get something like...

Conditions: (operator: Equal left -> $val, right -> true,)

This is something based on a previous question/answer at How to use PHP-Parser to get the global variables name and change it.

So the current code is...

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

which will give...

left=$val PhpParser\Node\Expr\BinaryOp\Equal right=true
expression is `$val == true`
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55