0

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.

10
  • Do you mean, you want to check if they're defined before they're referenced? Commented Apr 22, 2021 at 18:23
  • Can you show what you have tried and a sample piece of code to show what you want to check for. Commented Apr 22, 2021 at 18:38
  • You should be able to check whether there's any assignment expression where the variable is the target. Commented Apr 22, 2021 at 18:52
  • IDEs like PhpStorm warn about using variables that aren't defined, so it's certainly possible to do this in static analysis. Whether it's possible for you depends on your programming skill. Commented Apr 22, 2021 at 18:53
  • I added some more information to my question. Hopefully this clears up my question. Commented Apr 22, 2021 at 19:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.