-2

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 Answers1

0

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.

Jerry
  • 3,391
  • 1
  • 19
  • 28
  • Thanks for idea. Unfortunally the real method is more complicated: it have type casts in issets like `$this->id = (int) $data['id'];` or `$this->y = (float) $data['y']` and setters like `$this->setCardsWidth((int) $data['width']);` – Vladimir Martsul Apr 09 '22 at 17:09
  • Just spitballing, but you could make setters for all the variables, which would also catch many of your errors. Having all variables set the same way might make the interface of your object easier to maintain. You could even have the setters follow a pattern that would allow you to something like `$setterName = 'set' . ucfirst($data[$field]); $this->$setterName($data[$field]);`. Ultimately the point is that only you can protect yourself from errors like the one you describe. – Jerry Apr 10 '22 at 18:01