Skip to content

Commit 75c57a7

Browse files
jrfnlsirbrillig
authored andcommitted
VariableAnalysisSniff::checkForGlobalDeclaration(): fix comment tolerance (#153)
PHP ignores comments in unexpected/unconventional places and so should the sniff. Includes adjusting an existing unit test. Without the fix, the adjusted unit test would cause test failures.
1 parent 0500066 commit 75c57a7

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -883,8 +883,12 @@ protected function checkForGlobalDeclaration(File $phpcsFile, $stackPtr, $varNam
883883
$tokens = $phpcsFile->getTokens();
884884

885885
// Are we a global declaration?
886-
// Search backwards for first token that isn't whitespace, comma or variable.
887-
$globalPtr = $phpcsFile->findPrevious([T_WHITESPACE, T_VARIABLE, T_COMMA], $stackPtr - 1, null, true, null, true);
886+
// Search backwards for first token that isn't whitespace/comment, comma or variable.
887+
$ignore = Tokens::$emptyTokens;
888+
$ignore[T_VARIABLE] = T_VARIABLE;
889+
$ignore[T_COMMA] = T_COMMA;
890+
891+
$globalPtr = $phpcsFile->findPrevious($ignore, $stackPtr - 1, null, true, null, true);
888892
if (($globalPtr === false) || ($tokens[$globalPtr]['code'] !== T_GLOBAL)) {
889893
return false;
890894
}

VariableAnalysis/Tests/CodeAnalysis/fixtures/FunctionWithGlobalVarFixture.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<?php
22

33
function function_with_global_var() {
4-
global $var, $var2, $unused; // should warn that `unused` is unused
4+
global $var, /*comment*/ $var2, $unused; // should warn that `unused` is unused
55

66
echo $var;
77
echo $var3; // should warn that var is undefined

0 commit comments

Comments
 (0)