PHP rules: a case which "Unused local variables should be removed" doesn't find out

80 views
Skip to first unread message

bmrs Geng

unread,
Jan 3, 2017, 1:47:27 AM1/3/17
to SonarQube
hi guys,

 I'm using sonarQube 5.6 and php code analyzer 2.8. And I'm facing  a case which a related rule doesn't find out. 
 The rule is : "Unused local variables should be removed". (php:S1481 ,  http://your_sonar_host/coding_rules#rule_key=php%3AS1481)
The interpretation is "If a local variable is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable is used for."
 The case goes like this :
    /* 
    * function:计算两个日期相隔多少年,多少月,多少天 
    * param string $date1[格式如:2011-11-5] 
    * param string $date2[格式如:2012-12-01] 
    * return array array('年','月','日'); 
    */ 
    static function diffDate( $date1, $date2 ){
        if( strtotime($date1) > strtotime($date2) ){
            $tmp = $date2; 
            $date2 = $date1; 
            $date1 = $tmp; 
        }
        list($Y1, $m1, $d1) = explode('-', $date1); 
        list($Y2, $m2, $d2) = explode('-', $date2); 
        $Y = $Y2 - $Y1;
        $m = $m2 - $m1;
        $d = $d2 - $d1;
        if( $d < 0 ){
            $d += (int)date('t', strtotime("-1 month $date2"));
            $m--;
        }
        if( $m < 0 ){
            $m += 12;
            $y--;
        }
        return array('year'=>$Y, 'month'=>$m, 'day'=>$d); 
    }

I think the variable $y ( in the code block if($m<0){$m+=12; $y--;}  )  violates the rule above, as it is a local variable and it is never be used. But PHP code analyzer does not find it out. 
I want to know why and how can I let this kind of case be found out?
$y is not declared. Is that why the analyzer doesn't find it out?

thanks.


yves.dubo...@sonarsource.com

unread,
Jan 4, 2017, 11:59:59 AM1/4/17
to SonarQube
Hello,

You are right, this is a false negative. Ticket SONARPHP-673 has been created to address the issue. In your case, the trouble does not originate from a missing declaration. It originates from $y being "shadowed" by $Y, which is wrong.

Thanks for reporting the issue!

Yves Dubois-Pèlerin
SonarSource team

bmrs Geng

unread,
Jan 8, 2017, 10:51:15 PM1/8/17
to SonarQube
thanks a lot. I appreciate your help. 
I'll check the Ticket SONARPHP-673 till it is fixed. Then I'll upgrade my sonarqube.
thanks again.

在 2017年1月5日星期四 UTC+8上午12:59:59,yves.dubo...@sonarsource.com写道:
Reply all
Reply to author
Forward
0 new messages