From 44f6423c53d8223cba27e21c0f9650e179d38e7a Mon Sep 17 00:00:00 2001 From: Manuel Strehl Date: Thu, 8 Oct 2015 12:29:43 +0200 Subject: [PATCH] detect isset() and mark found variables declared If you have code like if (isset($foo)) { $bar = $foo; } you already guard yourself against undefined variables. In this case the sniff should treat the variable as if it were declared. --- Sniffs/CodeAnalysis/VariableAnalysisSniff.php | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/Sniffs/CodeAnalysis/VariableAnalysisSniff.php b/Sniffs/CodeAnalysis/VariableAnalysisSniff.php index e822ad3..bba92af 100644 --- a/Sniffs/CodeAnalysis/VariableAnalysisSniff.php +++ b/Sniffs/CodeAnalysis/VariableAnalysisSniff.php @@ -785,7 +785,34 @@ protected function checkForFunctionPrototype( } return false; } + + /** + * isset() marks a variable as declared + */ + protected function checkForIsset( + PHP_CodeSniffer_File $phpcsFile, + $stackPtr, + $varName, + $currScope + ) { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + + // Are we an isset() parameter? + if (($openPtr = $this->findContainingBrackets($phpcsFile, $stackPtr)) === false) { + return false; + } + $catchPtr = $phpcsFile->findPrevious(T_WHITESPACE, + $openPtr - 1, null, true, null, true); + if (($catchPtr !== false) && + ($tokens[$catchPtr]['code'] === T_ISSET)) { + $this->markVariableAssignment($varName, $stackPtr, $currScope); + return true; + } + return false; + } + protected function checkForCatchBlock( PHP_CodeSniffer_File $phpcsFile, $stackPtr, @@ -1262,6 +1289,11 @@ protected function processVariable( return; } + // Are we an isset() parameter? + if ($this->checkForIsset($phpcsFile, $stackPtr, $varName, $currScope)) { + return; + } + // Are we a catch parameter? if ($this->checkForCatchBlock($phpcsFile, $stackPtr, $varName, $currScope)) { return; @@ -1495,4 +1527,4 @@ protected function processScopeClose( } }//end class -?> \ No newline at end of file +?>