Skip to content

Commit 3dfd71a

Browse files
committed
Add isRequireInScopeAfter and use allowUnusedVariablesBeforeRequire
1 parent 0002a10 commit 3dfd71a

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

VariableAnalysis/Lib/Helpers.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,4 +369,34 @@ public static function areFollowingArgumentsUsed(VariableInfo $varInfo, ScopeInf
369369
}
370370
return false;
371371
}
372+
373+
/**
374+
* @param File $phpcsFile
375+
* @param VariableInfo $varInfo
376+
* @param ScopeInfo $scopeInfo
377+
*
378+
* @return bool
379+
*/
380+
public static function isRequireInScopeAfter(File $phpcsFile, VariableInfo $varInfo, ScopeInfo $scopeInfo) {
381+
$requireTokens = [
382+
T_REQUIRE,
383+
T_REQUIRE_ONCE,
384+
T_INCLUDE,
385+
T_INCLUDE_ONCE,
386+
];
387+
$indexToStartSearch = $varInfo->firstDeclared;
388+
if (! empty($varInfo->firstInitialized)) {
389+
$indexToStartSearch = $varInfo->firstInitialized;
390+
}
391+
$tokens = $phpcsFile->getTokens();
392+
$indexToStopSearch = isset($tokens[$scopeInfo->owner]['scope_closer']) ? $tokens[$scopeInfo->owner]['scope_closer'] : null;
393+
if (! is_int($indexToStartSearch) || ! is_int($indexToStopSearch)) {
394+
return false;
395+
}
396+
$requireTokenIndex = $phpcsFile->findNext($requireTokens, $indexToStartSearch + 1, $indexToStopSearch);
397+
if (is_int($requireTokenIndex)) {
398+
return true;
399+
}
400+
return false;
401+
}
372402
}

VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1417,6 +1417,9 @@ protected function processScopeCloseForVariable(File $phpcsFile, VariableInfo $v
14171417
} elseif (!empty($varInfo->firstInitialized)) {
14181418
$stackPtr = $varInfo->firstInitialized;
14191419
}
1420+
if ($this->allowUnusedVariablesBeforeRequire && Helpers::isRequireInScopeAfter($phpcsFile, $varInfo, $scopeInfo)) {
1421+
return;
1422+
}
14201423
if ($stackPtr) {
14211424
Helpers::debug("variable {$varInfo->name} at end of scope looks undefined");
14221425
$phpcsFile->addWarning(

0 commit comments

Comments
 (0)