Check whether variable is defined using nikic/php-parser

176 views Asked by At

I'm trying to build a static code analysis tool and I would like to check if the variables in a file are defined. Currently I'm using nikic/PHP-Parser (https://github.com/nikic/PHP-Parser), but I'm not sure if what I'm attempting is even possible.

So my question is: is it possible to check whether is (possibly) set. So does the variable contain a different value than null? Since the code is not executed in static analysis I feel like it might be impossible to "guess" whether the variable might be null, before giving it to a function for example.

An example:

$page = Expertise::find(get_the_ID());
$relatedNews = $page->connectedNews->take(-3)->reverse();

The second line might give us an exception in this case, when $page turned out to be null. I would like to detect these kinds of instabilities in the code using static analysis.

Here's a piece of code of what I'm attempting using PHP-Parser.

class NodeVisitor extends NodeVisitorAbstract
{
    public function enterNode(Node $node)
    {
        if ($node instanceof Node\Expr\Variable) {
            // is not null (is set)
            // or if that's not possible: is defined before reference?
            }
        }
    }

Edit: to be more clear on why I'm doing this, I'm trying to build an application that detects possible 500 errors without knowing anything about the execution of the code.

0

There are 0 answers