function AssignmentInConditionSniff::process
Same name in this branch
- 11.1.x vendor/slevomat/coding-standard/SlevomatCodingStandard/Sniffs/ControlStructures/AssignmentInConditionSniff.php \SlevomatCodingStandard\Sniffs\ControlStructures\AssignmentInConditionSniff::process()
Processes this test, when one of its tokens is encountered.
Parameters
\PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.:
int $stackPtr The position of the current token: in the stack passed in $tokens.
Return value
void
Overrides Sniff::process
File
-
vendor/
squizlabs/ php_codesniffer/ src/ Standards/ Generic/ Sniffs/ CodeAnalysis/ AssignmentInConditionSniff.php, line 78
Class
Namespace
PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysisCode
public function process(File $phpcsFile, $stackPtr) {
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Find the condition opener/closer.
if ($token['code'] === T_FOR) {
if (isset($token['parenthesis_opener'], $token['parenthesis_closer']) === false) {
return;
}
$semicolon = $phpcsFile->findNext(T_SEMICOLON, $token['parenthesis_opener'] + 1, $token['parenthesis_closer']);
if ($semicolon === false) {
return;
}
$opener = $semicolon;
$semicolon = $phpcsFile->findNext(T_SEMICOLON, $opener + 1, $token['parenthesis_closer']);
if ($semicolon === false) {
return;
}
$closer = $semicolon;
unset($semicolon);
}
else {
if ($token['code'] === T_CASE) {
if (isset($token['scope_opener']) === false) {
return;
}
$opener = $stackPtr;
$closer = $token['scope_opener'];
}
else {
if (isset($token['parenthesis_opener'], $token['parenthesis_closer']) === false) {
return;
}
$opener = $token['parenthesis_opener'];
$closer = $token['parenthesis_closer'];
}
}
//end if
$startPos = $opener;
do {
$hasAssignment = $phpcsFile->findNext($this->assignmentTokens, $startPos + 1, $closer);
if ($hasAssignment === false) {
return;
}
// Examine whether the left side is a variable.
$hasVariable = false;
$conditionStart = $startPos;
$altConditionStart = $phpcsFile->findPrevious($this->conditionStartTokens, $hasAssignment - 1, $startPos);
if ($altConditionStart !== false) {
$conditionStart = $altConditionStart;
}
for ($i = $hasAssignment; $i > $conditionStart; $i--) {
if (isset(Tokens::$emptyTokens[$tokens[$i]['code']]) === true) {
continue;
}
// If this is a variable or array, we've seen all we need to see.
if ($tokens[$i]['code'] === T_VARIABLE || $tokens[$i]['code'] === T_CLOSE_SQUARE_BRACKET) {
$hasVariable = true;
break;
}
// If this is a function call or something, we are OK.
if ($tokens[$i]['code'] === T_CLOSE_PARENTHESIS) {
break;
}
}
if ($hasVariable === true) {
$errorCode = 'Found';
if ($token['code'] === T_WHILE) {
$errorCode = 'FoundInWhileCondition';
}
$phpcsFile->addWarning('Variable assignment found within a condition. Did you mean to do a comparison ?', $hasAssignment, $errorCode);
}
$startPos = $hasAssignment;
} while ($startPos < $closer);
}