Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test(phpcs): Check for unused variables in PHPCS itself #446

Merged
merged 7 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -1657,7 +1657,7 @@ public static function setConfigData($key, $value, $temp=false)
// standards paths are added to the autoloader.
if ($key === 'installed_paths') {
$installedStandards = Standards::getInstalledStandardDetails();
foreach ($installedStandards as $name => $details) {
foreach ($installedStandards as $details) {
Autoload::addSearchPath($details['path'], $details['namespace']);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Files/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -1014,7 +1014,7 @@ protected function addMessage($error, $message, $line, $column, $code, $data, $s
continue;
}

foreach ($patterns as $pattern => $type) {
foreach (array_keys($patterns) as $pattern) {
klausi marked this conversation as resolved.
Show resolved Hide resolved
// While there is support for a type of each pattern
// (absolute or relative) we don't actually support it here.
$replacements = [
Expand Down
2 changes: 1 addition & 1 deletion src/Filters/Filter.php
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ protected function shouldProcessFile($path)
// complete extension list and make sure one is allowed.
$extensions = [];
array_shift($fileParts);
foreach ($fileParts as $part) {
while (empty($fileParts) === false) {
klausi marked this conversation as resolved.
Show resolved Hide resolved
$extensions[implode('.', $fileParts)] = 1;
array_shift($fileParts);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Generators/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public function __construct(Ruleset $ruleset)
{
$this->ruleset = $ruleset;

foreach ($ruleset->sniffs as $className => $sniffClass) {
foreach (array_keys($ruleset->sniffs) as $className) {
$file = Autoload::getLoadedFileName($className);
$docFile = str_replace(
DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR,
Expand Down
4 changes: 2 additions & 2 deletions src/Reports/Code.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public function generateFileReport($report, File $phpcsFile, $showSources=false,
// Determine the longest error message we will be showing.
$maxErrorLength = 0;
foreach ($report['messages'] as $line => $lineErrors) {
foreach ($lineErrors as $column => $colErrors) {
foreach ($lineErrors as $colErrors) {
foreach ($colErrors as $error) {
$length = strlen($error['message']);
if ($showSources === true) {
Expand Down Expand Up @@ -264,7 +264,7 @@ public function generateFileReport($report, File $phpcsFile, $showSources=false,

echo str_repeat('-', $width).PHP_EOL;

foreach ($lineErrors as $column => $colErrors) {
foreach ($lineErrors as $colErrors) {
foreach ($colErrors as $error) {
$padding = ($maxLineNumLength - strlen($line));
echo 'LINE '.str_repeat(' ', $padding).$line.': ';
Expand Down
4 changes: 2 additions & 2 deletions src/Reports/Full.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public function generateFileReport($report, File $phpcsFile, $showSources=false,
// Make sure the report width isn't too big.
$maxErrorLength = 0;
foreach ($report['messages'] as $line => $lineErrors) {
foreach ($lineErrors as $column => $colErrors) {
foreach ($lineErrors as $colErrors) {
jrfnl marked this conversation as resolved.
Show resolved Hide resolved
foreach ($colErrors as $error) {
// Start with the presumption of a single line error message.
$length = strlen($error['message']);
Expand Down Expand Up @@ -138,7 +138,7 @@ public function generateFileReport($report, File $phpcsFile, $showSources=false,
$beforeAfterLength = strlen($beforeMsg.$afterMsg);

foreach ($report['messages'] as $line => $lineErrors) {
foreach ($lineErrors as $column => $colErrors) {
foreach ($lineErrors as $colErrors) {
foreach ($colErrors as $error) {
$errorMsg = wordwrap(
$error['message'],
Expand Down
4 changes: 2 additions & 2 deletions src/Reports/Source.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ public function generateFileReport($report, File $phpcsFile, $showSources=false,

$sources = [];

foreach ($report['messages'] as $line => $lineErrors) {
foreach ($lineErrors as $column => $colErrors) {
foreach ($report['messages'] as $lineErrors) {
foreach ($lineErrors as $colErrors) {
foreach ($colErrors as $error) {
$src = $error['source'];
if (isset($sources[$src]) === false) {
Expand Down
2 changes: 1 addition & 1 deletion src/Reports/VersionControl.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public function generateFileReport($report, File $phpcsFile, $showSources=false,

$praiseCache[$author]['bad']++;

foreach ($lineErrors as $column => $colErrors) {
foreach ($lineErrors as $colErrors) {
foreach ($colErrors as $error) {
$authorCache[$author]++;

Expand Down
6 changes: 3 additions & 3 deletions src/Ruleset.php
Original file line number Diff line number Diff line change
Expand Up @@ -1381,7 +1381,7 @@ public function populateTokenListeners()
// Construct a list of listeners indexed by token being listened for.
$this->tokenListeners = [];

foreach ($this->sniffs as $sniffClass => $sniffObject) {
foreach (array_keys($this->sniffs) as $sniffClass) {
$this->sniffs[$sniffClass] = null;
$this->sniffs[$sniffClass] = new $sniffClass();

Expand Down Expand Up @@ -1417,7 +1417,7 @@ public function populateTokenListeners()

$ignorePatterns = [];
$patterns = $this->getIgnorePatterns($sniffCode);
foreach ($patterns as $pattern => $type) {
foreach (array_keys($patterns) as $pattern) {
$replacements = [
'\\,' => ',',
'*' => '.*',
Expand All @@ -1428,7 +1428,7 @@ public function populateTokenListeners()

$includePatterns = [];
$patterns = $this->getIncludePatterns($sniffCode);
foreach ($patterns as $pattern => $type) {
foreach (array_keys($patterns) as $pattern) {
$replacements = [
'\\,' => ',',
'*' => '.*',
Expand Down
4 changes: 2 additions & 2 deletions src/Runner.php
Original file line number Diff line number Diff line change
Expand Up @@ -333,11 +333,11 @@ public function init()

// Create this class so it is autoloaded and sets up a bunch
// of PHP_CodeSniffer-specific token type constants.
$tokens = new Tokens();
new Tokens();
klausi marked this conversation as resolved.
Show resolved Hide resolved

// Allow autoloading of custom files inside installed standards.
$installedStandards = Standards::getInstalledStandardDetails();
foreach ($installedStandards as $name => $details) {
foreach ($installedStandards as $details) {
Autoload::addSearchPath($details['path'], $details['namespace']);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Sniffs/AbstractVariableSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ final protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $cu

// Just make sure this isn't a variable in a function declaration.
if ($inFunction === false && isset($tokens[$stackPtr]['nested_parenthesis']) === true) {
foreach ($tokens[$stackPtr]['nested_parenthesis'] as $opener => $closer) {
foreach (array_keys($tokens[$stackPtr]['nested_parenthesis']) as $opener) {
if (isset($tokens[$opener]['parenthesis_owner']) === false) {
// Check if this is a USE statement for a closure.
$prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($opener - 1), null, true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ public function isArrayStatic(File $phpcsFile, $arrayToken)
{
$tokens = $phpcsFile->getTokens();

$arrayEnd = null;
klausi marked this conversation as resolved.
Show resolved Hide resolved
if ($tokens[$arrayToken]['code'] === T_OPEN_SHORT_ARRAY) {
$start = $arrayToken;
$end = $tokens[$arrayToken]['bracket_closer'];
Expand Down
2 changes: 1 addition & 1 deletion src/Standards/Generic/Sniffs/Files/InlineHTMLSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function process(File $phpcsFile, $stackPtr)
{
// Allow a byte-order mark.
$tokens = $phpcsFile->getTokens();
foreach ($this->bomDefinitions as $bomName => $expectedBomHex) {
foreach ($this->bomDefinitions as $expectedBomHex) {
$bomByteLength = (strlen($expectedBomHex) / 2);
$htmlBomHex = bin2hex(substr($tokens[0]['content'], 0, $bomByteLength));
if ($htmlBomHex === $expectedBomHex && strlen($tokens[0]['content']) === $bomByteLength) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function process(File $phpcsFile, $stackPtr)
if ($stackPtr > 0) {
// Allow a byte-order mark.
$tokens = $phpcsFile->getTokens();
foreach ($this->bomDefinitions as $bomName => $expectedBomHex) {
foreach ($this->bomDefinitions as $expectedBomHex) {
$bomByteLength = (strlen($expectedBomHex) / 2);
$htmlBomHex = bin2hex(substr($tokens[0]['content'], 0, $bomByteLength));
if ($htmlBomHex === $expectedBomHex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public function process(File $phpcsFile, $stackPtr)
}

$allProperties = ($properties + $this->properties);
foreach ($allProperties as $key => $value) {
foreach (array_keys($allProperties) as $key) {
if (isset($properties[$key]) === true
&& isset($this->properties[$key]) === false
) {
Expand Down
1 change: 0 additions & 1 deletion src/Standards/Generic/Tests/Debug/JSHintUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ final class JSHintUnitTest extends AbstractSniffUnitTest
*/
protected function shouldSkipTest()
{
$rhinoPath = Config::getExecutablePath('rhino');
$jshintPath = Config::getExecutablePath('jshint');
if ($jshintPath === null) {
return true;
Expand Down
2 changes: 1 addition & 1 deletion src/Standards/PEAR/Sniffs/Files/IncludingFileSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public function process(File $phpcsFile, $stackPtr)
// of a condition. If that's the case then we need to process it as being
// within a condition, as they are checking the return value.
if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) {
foreach ($tokens[$stackPtr]['nested_parenthesis'] as $left => $right) {
foreach (array_keys($tokens[$stackPtr]['nested_parenthesis']) as $left) {
if (isset($tokens[$left]['parenthesis_owner']) === true) {
$inCondition = true;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Standards/Squiz/Sniffs/Commenting/FileCommentSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ public function process(File $phpcsFile, $stackPtr)

// Check if the tags are in the correct position.
$pos = 0;
foreach ($required as $tag => $true) {
foreach (array_keys($required) as $tag) {
if (in_array($tag, $foundTags, true) === false) {
$error = 'Missing %s tag in file comment';
$data = [$tag];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ protected function processReturn(File $phpcsFile, $stackPtr, $commentStart)
// Check return type (can be multiple, separated by '|').
$typeNames = explode('|', $returnType);
$suggestedNames = [];
foreach ($typeNames as $i => $typeName) {
foreach ($typeNames as $typeName) {
$suggestedName = Common::suggestType($typeName);
if (in_array($suggestedName, $suggestedNames, true) === false) {
$suggestedNames[] = $suggestedName;
Expand Down Expand Up @@ -531,7 +531,7 @@ protected function processParams(File $phpcsFile, $stackPtr, $commentStart)
$phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content);

// Fix up the indent of additional comment lines.
foreach ($param['commentLines'] as $lineNum => $line) {
foreach (array_keys($param['commentLines']) as $lineNum) {
if ($lineNum === 0
|| $param['commentLines'][$lineNum]['indent'] === 0
) {
Expand Down Expand Up @@ -677,7 +677,7 @@ protected function checkSpacingAfterParamType(File $phpcsFile, $param, $maxType,

// Fix up the indent of additional comment lines.
$diff = ($param['type_space'] - $spaces);
foreach ($param['commentLines'] as $lineNum => $line) {
foreach (array_keys($param['commentLines']) as $lineNum) {
if ($lineNum === 0
|| $param['commentLines'][$lineNum]['indent'] === 0
) {
Expand Down Expand Up @@ -735,7 +735,7 @@ protected function checkSpacingAfterParamName(File $phpcsFile, $param, $maxVar,
$phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content);

// Fix up the indent of additional comment lines.
foreach ($param['commentLines'] as $lineNum => $line) {
foreach (array_keys($param['commentLines']) as $lineNum) {
if ($lineNum === 0
|| $param['commentLines'][$lineNum]['indent'] === 0
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ public function process(File $phpcsFile, $stackPtr)
continue;
}

foreach ($throwTags as $tag => $ignore) {
foreach (array_keys($throwTags) as $tag) {
if (strrpos($tag, $throw) === (strlen($tag) - strlen($throw))) {
continue 2;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ public function process(File $phpcsFile, $stackPtr)
if (in_array($commentCloser, $acceptedClosers, true) === false) {
$error = 'Inline comments must end in %s';
$ender = '';
foreach ($acceptedClosers as $closerName => $symbol) {
foreach (array_keys($acceptedClosers) as $closerName) {
$ender .= ' '.$closerName.',';
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public function process(File $phpcsFile, $stackPtr)
// Special case for (trailing) comments within multi-line control structures.
if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) {
$nestedParens = $tokens[$stackPtr]['nested_parenthesis'];
foreach ($nestedParens as $open => $close) {
foreach (array_keys($nestedParens) as $open) {
if (isset($tokens[$open]['parenthesis_owner']) === true
&& isset($this->controlStructureExceptions[$tokens[$tokens[$open]['parenthesis_owner']]['code']]) === true
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public function processMemberVar(File $phpcsFile, $stackPtr)
// Check var type (can be multiple, separated by '|').
$typeNames = explode('|', $varType);
$suggestedNames = [];
foreach ($typeNames as $i => $typeName) {
foreach ($typeNames as $typeName) {
$suggestedName = Common::suggestType($typeName);
if (in_array($suggestedName, $suggestedNames, true) === false) {
$suggestedNames[] = $suggestedName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,6 @@ public function processBracket($phpcsFile, $openBracket, $tokens, $type='functio
}//end if

// Each line between the brackets should contain a single parameter.
$lastComma = null;
for ($i = ($openBracket + 1); $i < $closeBracket; $i++) {
// Skip brackets, like arrays, as they can contain commas.
if (isset($tokens[$i]['bracket_opener']) === true) {
Expand Down
17 changes: 6 additions & 11 deletions src/Standards/Squiz/Sniffs/PHP/CommentedOutCodeSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -238,23 +238,18 @@ public function process(File $phpcsFile, $stackPtr)
];
$emptyTokens += Tokens::$phpcsCommentTokens;

$numComment = 0;
$numPossible = 0;
$numCode = 0;
$numNonWhitespace = 0;

for ($i = 0; $i < $numTokens; $i++) {
if (isset($emptyTokens[$stringTokens[$i]['code']]) === true) {
// Looks like comment.
$numComment++;
} else if (isset(Tokens::$comparisonTokens[$stringTokens[$i]['code']]) === true
|| isset(Tokens::$arithmeticTokens[$stringTokens[$i]['code']]) === true
|| $stringTokens[$i]['code'] === T_GOTO_LABEL
) {
// Do not count comments.
if (isset($emptyTokens[$stringTokens[$i]['code']]) === false
// Commented out HTML/XML and other docs contain a lot of these
// characters, so it is best to not use them directly.
$numPossible++;
} else {
&& isset(Tokens::$comparisonTokens[$stringTokens[$i]['code']]) === false
&& isset(Tokens::$arithmeticTokens[$stringTokens[$i]['code']]) === false
&& $stringTokens[$i]['code'] !== T_GOTO_LABEL
) {
klausi marked this conversation as resolved.
Show resolved Hide resolved
// Looks like code.
$numCode++;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) {
foreach ($tokens[$stackPtr]['nested_parenthesis'] as $open => $close) {
foreach (array_keys($tokens[$stackPtr]['nested_parenthesis']) as $open) {
if (isset($tokens[$open]['parenthesis_owner']) === true) {
// Any owner means we are not just a simple statement.
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function process(File $phpcsFile, $stackPtr)
// Ignore assignments in WHILE loop conditions.
if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) {
$nested = $tokens[$stackPtr]['nested_parenthesis'];
foreach ($nested as $opener => $closer) {
foreach (array_keys($nested) as $opener) {
if (isset($tokens[$opener]['parenthesis_owner']) === true
&& $tokens[$tokens[$opener]['parenthesis_owner']]['code'] === T_WHILE
) {
Expand Down Expand Up @@ -168,7 +168,7 @@ public function process(File $phpcsFile, $stackPtr)
T_FOR => T_FOR,
T_MATCH => T_MATCH,
];
foreach ($nested as $opener => $closer) {
foreach (array_keys($nested) as $opener) {
if (isset($tokens[$opener]['parenthesis_owner']) === true
&& isset($controlStructures[$tokens[$tokens[$opener]['parenthesis_owner']]['code']]) === true
) {
Expand Down
1 change: 0 additions & 1 deletion src/Tokenizers/CSS.php
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,6 @@ public function tokenize($string)
if ($finalTokens[($numTokens - 2)]['content'] === '') {
unset($finalTokens[($numTokens - 2)]);
$finalTokens = array_values($finalTokens);
$numTokens = count($finalTokens);
klausi marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/Tokenizers/JS.php
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ public function tokenize($string)
}

$maxTokenLength = 0;
foreach ($this->tokenValues as $token => $values) {
foreach (array_keys($this->tokenValues) as $token) {
if (strlen($token) > $maxTokenLength) {
$maxTokenLength = strlen($token);
}
Expand Down Expand Up @@ -1188,7 +1188,7 @@ public function processAdditional()
}
}
} else if ($this->tokens[$i]['code'] === T_CLOSE_OBJECT) {
$opener = array_pop($classStack);
array_pop($classStack);
} else if ($this->tokens[$i]['code'] === T_COLON) {
// If it is a scope opener, it belongs to a
// DEFAULT or CASE statement.
Expand Down
3 changes: 2 additions & 1 deletion src/Util/Common.php
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,8 @@ public static function getSniffCode($sniffClass)
}

$category = array_pop($parts);
$sniffDir = array_pop($parts);
// Remove Sniff directory.
array_pop($parts);
$standard = array_pop($parts);
klausi marked this conversation as resolved.
Show resolved Hide resolved
$code = $standard.'.'.$category.'.'.$sniff;
return $code;
Expand Down
6 changes: 3 additions & 3 deletions tests/Core/File/GetMemberPropertiesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1094,7 +1094,7 @@ public function testNotClassPropertyException($identifier)
$this->expectRunTimeException('$stackPtr is not a class member var');

$variable = $this->getTargetToken($identifier, T_VARIABLE);
$result = self::$phpcsFile->getMemberProperties($variable);
self::$phpcsFile->getMemberProperties($variable);

}//end testNotClassPropertyException()

Expand Down Expand Up @@ -1130,8 +1130,8 @@ public function testNotAVariableException()
{
$this->expectRunTimeException('$stackPtr must be of type T_VARIABLE');

$next = $this->getTargetToken('/* testNotAVariable */', T_RETURN);
$result = self::$phpcsFile->getMemberProperties($next);
$next = $this->getTargetToken('/* testNotAVariable */', T_RETURN);
self::$phpcsFile->getMemberProperties($next);

}//end testNotAVariableException()

Expand Down
Loading