How to catch php spelling errors with static analyzers?

84 views Asked by At

I was made a mistake yesterday and spent hours to fix it. I have method like this

{
    if (isset($data['y'])) {
        $this->y = $data['y'];
    }

    if (isset($data['z'])) {
        $this->y = $data['z']; // <- error here
    }
}

And yes, I assign $this->y two times instead of one y and one z :-(

So question: can any static analyze tools catch such errors? I have PHP Storm and Rector, PHPStan, PHP CS Fixer in my CI toolchain but they missed this error.

1

There are 1 answers

2
Jerry On

This isn't so much an answer, but it's too complicated to put in a comment.

As the comments pointed out, there's simply no way for a robot to figure out that what you wrote isn't what you intended. The easiest solution is to live with human frailty and debug your code.

But that doesn't mean you can't write your code to better express your intent. Consider:

{
    $fields = ['x', 'y'];

    foreach ($fields as $field) {
        if (isset($data[$field]) {
            $this->$field = $data[$field];
        }
    }
}

Now you have expressed in you code that you only want to assign like-named fields.