简体   繁体   English

如何使用 static 分析器捕获 php 拼写错误?

[英]How to catch php spelling errors with static analyzers?

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 :-(是的,我分配$this->y两次而不是一次y和一次z :-(

So question: can any static analyze tools catch such errors?所以问题:任何static分析工具都可以捕获此类错误吗? I have PHP Storm and Rector, PHPStan, PHP CS Fixer in my CI toolchain but they missed this error.我的 CI 工具链中有 PHP Storm 和 Rector、PHPStan、PHP CS Fixer,但他们错过了这个错误。

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.现在您已经在代码中表达了您只想分配同名字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM