3
* Squiz_Sniffs_PHP_DisallowComparisonAssignmentSniff.
8
* @package PHP_CodeSniffer
9
* @author Greg Sherwood <gsherwood@squiz.net>
10
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
11
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
12
* @link http://pear.php.net/package/PHP_CodeSniffer
16
* Squiz_Sniffs_PHP_DisallowComparisonAssignmentSniff.
18
* Ensures that the value of a comparison is not assigned to a variable.
21
* @package PHP_CodeSniffer
22
* @author Greg Sherwood <gsherwood@squiz.net>
23
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
24
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
25
* @version Release: 1.3.4
26
* @link http://pear.php.net/package/PHP_CodeSniffer
28
class Squiz_Sniffs_PHP_DisallowComparisonAssignmentSniff implements PHP_CodeSniffer_Sniff
33
* Returns an array of tokens this test wants to listen for.
37
public function register()
39
return array(T_EQUAL);
45
* Processes this test, when one of its tokens is encountered.
47
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
48
* @param int $stackPtr The position of the current token
49
* in the stack passed in $tokens.
53
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
55
$tokens = $phpcsFile->getTokens();
57
// Ignore default value assignments in function definitions.
58
$function = $phpcsFile->findPrevious(T_FUNCTION, ($stackPtr - 1));
59
if ($function !== false) {
60
$opener = $tokens[$function]['parenthesis_opener'];
61
$closer = $tokens[$function]['parenthesis_closer'];
62
if ($opener < $stackPtr && $closer > $stackPtr) {
67
// Ignore values in array definitions.
68
$array = $phpcsFile->findNext(
77
if ($array !== false) {
81
// Ignore function calls.
88
$next = $phpcsFile->findNext($ignore, ($stackPtr + 1), null, true);
89
if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS
90
&& $tokens[($next - 1)]['code'] === T_STRING
92
// Code will look like: $var = myFunction(
93
// and will be ignored.
97
$endStatement = $phpcsFile->findNext(T_SEMICOLON, ($stackPtr + 1));
98
for ($i = ($stackPtr + 1); $i < $endStatement; $i++) {
99
if (in_array($tokens[$i]['code'], PHP_CodeSniffer_Tokens::$comparisonTokens) === true) {
100
$error = 'The value of a comparison must not be assigned to a variable';
101
$phpcsFile->addError($error, $stackPtr, 'AssignedComparison');
105
if (in_array($tokens[$i]['code'], PHP_CodeSniffer_Tokens::$booleanOperators) === true
106
|| $tokens[$i]['code'] === T_BOOLEAN_NOT
108
$error = 'The value of a boolean operation must not be assigned to a variable';
109
$phpcsFile->addError($error, $stackPtr, 'AssignedBool');