Skip to content

Commit

Permalink
Generate warning for use of else and elseif
Browse files Browse the repository at this point in the history
  • Loading branch information
chadicus committed Jan 25, 2016
1 parent 971fac1 commit a9a4e1b
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<documentation title="ElseIf and Else Declarations">
<standard>
<![CDATA[
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.
]]>
</standard>
<code_comparison>
<code title="Valid: Method returns early to avoid use of else.">
<![CDATA[
public function bar($flag)
{
if ($flag) {
// perform action in true case
return;
}
// perform action in false case
}
]]>
</code>
<code title="Invalid: Else statement used.">
<![CDATA[
public function bar($flag)
{
if ($flag) {
// perform action in true case
<em>} else {</em>
// perform action in false case
}
}
]]>
</code>
</code_comparison>
</documentation>
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php
/**
* Generates a warning if else or elseif control structures are used.
*/
final class Chadicus_Sniffs_ControlStructures_ElseIfAndElseDeclarationSniff implements PHP_CodeSniffer_Sniff
{

/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return [T_ELSEIF, T_ELSE];
}

/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param integer $stackPtr The position of the current token in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$error = 'Use of ELSE and ELSEIF is discouraged. 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.';
$phpcsFile->addWarning($error, $stackPtr, 'Discouraged');
}
}

0 comments on commit a9a4e1b

Please sign in to comment.