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 5 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/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
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
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
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
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
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
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
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
2 changes: 1 addition & 1 deletion src/Tokenizers/JS.php
Original file line number Diff line number Diff line change
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
4 changes: 2 additions & 2 deletions tests/Core/Ruleset/ExplainTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -249,8 +249,8 @@ public function testExplainWillExplainEachStandardSeparately()

$this->expectOutputString($expected);

$runner = new Runner();
$exitCode = $runner->runPHPCS();
$runner = new Runner();
$runner->runPHPCS();

}//end testExplainWillExplainEachStandardSeparately()

Expand Down
2 changes: 0 additions & 2 deletions tests/Core/Ruleset/RuleInclusionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -439,8 +439,6 @@ public function testSettingInvalidPropertiesOnStandardsAndCategoriesSilentlyFail
{
$this->assertArrayHasKey($sniffClass, self::$ruleset->sniffs, 'Sniff class '.$sniffClass.' not listed in registered sniffs');

$sniffObject = self::$ruleset->sniffs[$sniffClass];

$hasProperty = (new ReflectionObject(self::$ruleset->sniffs[$sniffClass]))->hasProperty($propertyName);
$errorMsg = sprintf('Property %s registered for sniff %s which does not support it', $propertyName, $sniffClass);
$this->assertFalse($hasProperty, $errorMsg);
Expand Down
11 changes: 4 additions & 7 deletions tests/Core/Ruleset/SetSniffPropertyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public function testSetPropertyThrowsErrorOnInvalidProperty()
// Set up the ruleset.
$standard = __DIR__.'/SetPropertyThrowsErrorOnInvalidPropertyTest.xml';
$config = new ConfigDouble(["--standard=$standard"]);
$ruleset = new Ruleset($config);
new Ruleset($config);

}//end testSetPropertyThrowsErrorOnInvalidProperty()

Expand All @@ -175,7 +175,7 @@ public function testSetPropertyThrowsErrorWhenPropertyOnlyAllowedViaAttribute()
// Set up the ruleset.
$standard = __DIR__.'/SetPropertyNotAllowedViaAttributeTest.xml';
$config = new ConfigDouble(["--standard=$standard"]);
$ruleset = new Ruleset($config);
new Ruleset($config);

}//end testSetPropertyThrowsErrorWhenPropertyOnlyAllowedViaAttribute()

Expand All @@ -193,7 +193,7 @@ public function testSetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForStand
// Set up the ruleset.
$standard = __DIR__.'/SetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForStandardTest.xml';
$config = new ConfigDouble(["--standard=$standard"]);
$ruleset = new Ruleset($config);
new Ruleset($config);

}//end testSetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForStandard()

Expand All @@ -211,7 +211,7 @@ public function testSetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForCateg
// Set up the ruleset.
$standard = __DIR__.'/SetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForCategoryTest.xml';
$config = new ConfigDouble(["--standard=$standard"]);
$ruleset = new Ruleset($config);
new Ruleset($config);

}//end testSetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForCategory()

Expand Down Expand Up @@ -383,16 +383,13 @@ public function testDirectCallWithOldArrayFormatThrowsDeprecationNotice()
}

$name = 'AllowedAsDeclared';
$sniffCode = "Fixtures.SetProperty.{$name}";
$sniffClass = 'Fixtures\Sniffs\SetProperty\\'.$name.'Sniff';

// Set up the ruleset.
$standard = __DIR__."/SetProperty{$name}Test.xml";
$config = new ConfigDouble(["--standard=$standard"]);
$ruleset = new Ruleset($config);

$propertyName = 'arbitrarystring';

$ruleset->setSniffProperty(
$sniffClass,
'arbitrarystring',
Expand Down
2 changes: 0 additions & 2 deletions tests/Core/Tokenizer/BackfillFnTokenTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -503,8 +503,6 @@ public function testTernary()
*/
public function testTernaryWithTypes()
{
$tokens = $this->phpcsFile->getTokens();

$token = $this->getTargetToken('/* testTernaryWithTypes */', T_FN);
$this->backfillHelper($token);
$this->scopePositionTestHelper($token, 15, 27);
Expand Down
2 changes: 1 addition & 1 deletion tests/Core/Tokenizer/StableCommentWhitespaceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function testCommentTokenization($testMarker, $expectedTokens)
$tokens = $this->phpcsFile->getTokens();
$comment = $this->getTargetToken($testMarker, Tokens::$commentTokens);

foreach ($expectedTokens as $key => $tokenInfo) {
foreach ($expectedTokens as $tokenInfo) {
$this->assertSame(
constant($tokenInfo['type']),
$tokens[$comment]['code'],
Expand Down
2 changes: 1 addition & 1 deletion tests/Core/Tokenizer/StableCommentWhitespaceWinTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function testCommentTokenization($testMarker, $expectedTokens)
$tokens = $this->phpcsFile->getTokens();
$comment = $this->getTargetToken($testMarker, Tokens::$commentTokens);

foreach ($expectedTokens as $key => $tokenInfo) {
foreach ($expectedTokens as $tokenInfo) {
$this->assertSame(
constant($tokenInfo['type']),
$tokens[$comment]['code'],
Expand Down
2 changes: 1 addition & 1 deletion tests/Core/Tokenizer/UndoNamespacedNameSingleTokenTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function testIdentifierTokenization($testMarker, $expectedTokens)
$tokens = $this->phpcsFile->getTokens();
$identifier = $this->getTargetToken($testMarker, constant($expectedTokens[0]['type']));

foreach ($expectedTokens as $key => $tokenInfo) {
foreach ($expectedTokens as $tokenInfo) {
$this->assertSame(
constant($tokenInfo['type']),
$tokens[$identifier]['code'],
Expand Down
4 changes: 2 additions & 2 deletions tests/Standards/AbstractSniffUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ public function generateFailureMessages(LocalFile $file)
$failureMessages = [];

foreach ($foundErrors as $line => $lineErrors) {
foreach ($lineErrors as $column => $errors) {
foreach ($lineErrors as $errors) {
klausi marked this conversation as resolved.
Show resolved Hide resolved
if (isset($allProblems[$line]) === false) {
$allProblems[$line] = [
'expected_errors' => 0,
Expand Down Expand Up @@ -310,7 +310,7 @@ public function generateFailureMessages(LocalFile $file)
}

foreach ($foundWarnings as $line => $lineWarnings) {
foreach ($lineWarnings as $column => $warnings) {
foreach ($lineWarnings as $warnings) {
if (isset($allProblems[$line]) === false) {
$allProblems[$line] = [
'expected_errors' => 0,
Expand Down
2 changes: 0 additions & 2 deletions tests/Standards/AllSniffs.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ public static function suite()

$suite = new TestSuite('PHP CodeSniffer Standards');

$isInstalled = !is_file(__DIR__.'/../../autoload.php');

// Optionally allow for ignoring the tests for one or more standards.
$ignoreTestsForStandards = getenv('PHPCS_IGNORE_TESTS');
if ($ignoreTestsForStandards === false) {
Expand Down
2 changes: 1 addition & 1 deletion tests/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

require_once __DIR__.'/../autoload.php';

$tokens = new \PHP_CodeSniffer\Util\Tokens();
new \PHP_CodeSniffer\Util\Tokens();
klausi marked this conversation as resolved.
Show resolved Hide resolved

// Compatibility for PHPUnit < 6 and PHPUnit 6+.
if (class_exists('PHPUnit_Framework_TestSuite') === true && class_exists('PHPUnit\Framework\TestSuite') === false) {
Expand Down