Skip to content

Commit

Permalink
ReferenceSniff: Fix false positive with bitwise and (#162)
Browse files Browse the repository at this point in the history
Co-authored-by: matt <[email protected]>
Co-authored-by: Michał Bundyra <[email protected]>
  • Loading branch information
3 people authored Feb 15, 2022
1 parent e47e6af commit cd0c4b0
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 12 deletions.
16 changes: 4 additions & 12 deletions src/WebimpressCodingStandard/Sniffs/Formatting/ReferenceSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,9 @@
use function in_array;

use const T_BITWISE_AND;
use const T_COMMA;
use const T_NEW;
use const T_OPEN_PARENTHESIS;
use const T_OPEN_SHORT_ARRAY;
use const T_STRING;
use const T_WHITESPACE;

class ReferenceSniff implements Sniff
Expand All @@ -35,6 +33,10 @@ public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();

if (! $phpcsFile->isReference($stackPtr)) {
return;
}

$next = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, true);
if ($tokens[$next]['code'] === T_NEW) {
$error = 'Reference operator is redundant before new keyword (objects are always passed by reference)';
Expand All @@ -49,16 +51,6 @@ public function process(File $phpcsFile, $stackPtr)

$prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, $stackPtr - 1, null, true);

$tokenCodes = Tokens::$assignmentTokens + [
T_COMMA => T_COMMA,
T_OPEN_PARENTHESIS => T_OPEN_PARENTHESIS,
T_OPEN_SHORT_ARRAY => T_OPEN_SHORT_ARRAY,
T_STRING => T_STRING,
];
if (! in_array($tokens[$prev]['code'], $tokenCodes, true)) {
return;
}

// One space before &
if ($tokens[$prev]['line'] === $tokens[$stackPtr]['line']
&& ! in_array($tokens[$stackPtr - 1]['code'], [T_WHITESPACE, T_OPEN_PARENTHESIS, T_OPEN_SHORT_ARRAY], true)
Expand Down
10 changes: 10 additions & 0 deletions test/Sniffs/Formatting/ReferenceUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,13 @@ $a = &new \DateTime();
$b = & new \DateTime();
$c =& new \DateTime();
$d =&new \DateTime();

class ReferenceClass
{
public int $flag = 1;

public function isFlagged()
{
return (bool) ($this->flag & 4);
}
}
10 changes: 10 additions & 0 deletions test/Sniffs/Formatting/ReferenceUnitTest.inc.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,13 @@ $a = new \DateTime();
$b = new \DateTime();
$c = new \DateTime();
$d =new \DateTime();

class ReferenceClass
{
public int $flag = 1;

public function isFlagged()
{
return (bool) ($this->flag & 4);
}
}

0 comments on commit cd0c4b0

Please sign in to comment.