squizlabs / PHP_CodeSniffer

PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.
BSD 3-Clause "New" or "Revised" License
10.67k stars 1.48k forks source link

Feature request - warn of empty while() loop #864

Closed wturrell closed 8 years ago

wturrell commented 8 years ago

i.e. warn you if you've left a while conditional that contains no statements in your code, because it will execute forever.

aik099 commented 8 years ago

Not sure, but maybe there is a sniff, that checks for while ( true ) { ... } constructs, aka infinite loops. I guess it can be adapted to handle empty condition case as well.

aik099 commented 8 years ago

Ups. I've mistaken it with Generic.CodeAnalysis.UnconditionalIfStatement sniff, that checked that IF/ELSEIF had only true or false in their condition.

Having sniff to detect infinite loops can be useful.

h3xx commented 8 years ago

i.e. warn you if you've left a while conditional that contains no statements in your code, because it will execute forever.

I'm not sure what you mean by "while conditional that contains no statements."

If you mean this:

<?php
while () {
}

That's not valid PHP code:

PHP Parse error:  syntax error, unexpected ')' in /home/dchurch/qq.php on line 3
wturrell commented 8 years ago

I meant:

<?php
while ($foo == 'bar') {
}

The scenario was I'd got as far as writing that much of the while, got distracted by something else and switched away from my IDE (which auto-saved the file in the meantime), and then spent a few minutes wondering why all the pages on my development server were timing out…

aik099 commented 8 years ago

Sure. Better to detect that issue early during CS checking phase, because once you've got infinite page loading it's hard to detect what causes it.

gsherwood commented 8 years ago

Try including the sniff Generic.CodeAnalysis.EmptyStatement. For this specific code, you get this:

$ phpcs temp.php --standard=Generic --sniffs=Generic.CodeAnalysis.EmptyStatement

FILE: temp.php
----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
----------------------------------------------------------------------
 2 | ERROR | Empty WHILE statement detected
----------------------------------------------------------------------

Time: 15ms; Memory: 2.25Mb

It also checks a bunch of other code blocks like IF, ELSE, FOR, FOREACH etc.

Is that what you're after?

gsherwood commented 8 years ago

If this sniff doesn't do what you are after, please comment and I'll reopen.