Skip to content

Commit a9a4e1b

Browse files
committed
Generate warning for use of else and elseif
1 parent 971fac1 commit a9a4e1b

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<documentation title="ElseIf and Else Declarations">
2+
<standard>
3+
<![CDATA[
4+
An if expression with an else branch is never necessary. You can rewrite the conditions in a way that the else is not necessary and the code becomes simpler to read.
5+
]]>
6+
</standard>
7+
<code_comparison>
8+
<code title="Valid: Method returns early to avoid use of else.">
9+
<![CDATA[
10+
public function bar($flag)
11+
{
12+
if ($flag) {
13+
// perform action in true case
14+
return;
15+
}
16+
17+
// perform action in false case
18+
}
19+
]]>
20+
</code>
21+
<code title="Invalid: Else statement used.">
22+
<![CDATA[
23+
public function bar($flag)
24+
{
25+
if ($flag) {
26+
// perform action in true case
27+
<em>} else {</em>
28+
// perform action in false case
29+
}
30+
}
31+
]]>
32+
</code>
33+
</code_comparison>
34+
</documentation>
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
/**
3+
* Generates a warning if else or elseif control structures are used.
4+
*/
5+
final class Chadicus_Sniffs_ControlStructures_ElseIfAndElseDeclarationSniff implements PHP_CodeSniffer_Sniff
6+
{
7+
8+
/**
9+
* Returns an array of tokens this test wants to listen for.
10+
*
11+
* @return array
12+
*/
13+
public function register()
14+
{
15+
return [T_ELSEIF, T_ELSE];
16+
}
17+
18+
/**
19+
* Processes this test, when one of its tokens is encountered.
20+
*
21+
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
22+
* @param integer $stackPtr The position of the current token in the stack passed in $tokens.
23+
*
24+
* @return void
25+
*/
26+
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
27+
{
28+
$error = 'Use of ELSE and ELSEIF is discouraged. An if expression with an else branch is never necessary. You '
29+
. 'can rewrite the conditions in a way that the else is not necessary and the code becomes simpler to '
30+
. 'read.';
31+
$phpcsFile->addWarning($error, $stackPtr, 'Discouraged');
32+
}
33+
}

0 commit comments

Comments
 (0)