Skip to content

Commit

Permalink
Squiz/NonExecutableCode: fold duplicate code
Browse files Browse the repository at this point in the history
Follow up on commits 0e10f43 and 01754d9, which both deal with fixing bugs where the sniff would not handle if/elseif/else conditions without curly braces correctly.

This commit merges the two near duplicate code blocks, which the above mentioned commits introduced, each containing code doing essentially the same thing.

Also note that `T_ELSE` is handled separately now as `else` does not take parentheses and can therefore not be a parenthesis owner.

This change is already covered by pre-existing tests.
  • Loading branch information
jrfnl committed Oct 12, 2023
1 parent e83b12b commit 15fceb3
Showing 1 changed file with 7 additions and 30 deletions.
37 changes: 7 additions & 30 deletions src/Standards/Squiz/Sniffs/PHP/NonExecutableCodeSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,21 +94,13 @@ public function process(File $phpcsFile, $stackPtr)
}
}//end if

// Check if this token is actually part of a one-line IF or ELSE statement.
for ($i = ($stackPtr - 1); $i > 0; $i--) {
if ($tokens[$i]['code'] === T_CLOSE_PARENTHESIS) {
$i = $tokens[$i]['parenthesis_opener'];
continue;
} else if (isset(Tokens::$emptyTokens[$tokens[$i]['code']]) === true) {
continue;
}

break;
}

if ($tokens[$i]['code'] === T_IF
|| $tokens[$i]['code'] === T_ELSE
|| $tokens[$i]['code'] === T_ELSEIF
// This token may be part of an inline condition.
// If we find a closing parenthesis that belongs to a condition,
// or an "else", we should ignore this token.
if ($tokens[$prev]['code'] === T_ELSE
|| (isset($tokens[$prev]['parenthesis_owner']) === true
&& ($tokens[$tokens[$prev]['parenthesis_owner']]['code'] === T_IF
|| $tokens[$tokens[$prev]['parenthesis_owner']]['code'] === T_ELSEIF))
) {
return;
}
Expand Down Expand Up @@ -176,21 +168,6 @@ public function process(File $phpcsFile, $stackPtr)
}//end if
}//end if

// This token may be part of an inline condition.
// If we find a closing parenthesis that belongs to a condition
// we should ignore this token.
if (isset($tokens[$prev]['parenthesis_owner']) === true) {
$owner = $tokens[$prev]['parenthesis_owner'];
$ignore = [
T_IF => true,
T_ELSE => true,
T_ELSEIF => true,
];
if (isset($ignore[$tokens[$owner]['code']]) === true) {
return;
}
}

$ourConditions = array_keys($tokens[$stackPtr]['conditions']);

if (empty($ourConditions) === false) {
Expand Down

0 comments on commit 15fceb3

Please sign in to comment.