Skip to content

Commit

Permalink
Merge pull request #10 from jrbasso/fix-unusedlocalvar-compact
Browse files Browse the repository at this point in the history
Fix UnusedLocalVariable to recognize compact function.
  • Loading branch information
manuelpichler committed Dec 14, 2012
2 parents 158e1f5 + 008d4aa commit e478912
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/main/php/PHP/PMD/Rule/UnusedLocalVariable.php
Expand Up @@ -140,6 +140,13 @@ private function collectVariables(PHP_PMD_Node_AbstractCallable $node)
foreach ($node->findChildrenOfType('VariableDeclarator') as $variable) {
$this->collectVariable($variable);
}
foreach ($node->findChildrenOfType('FunctionPostfix') as $func) {
if ($func->getImage() === 'compact') {

This comment has been minimized.

Copy link
@svscorp

svscorp Jan 7, 2013

Contributor

Here is a little bug. In Symfony 2.1 $func->getImage() returns a string like "Acme/SomethingBundle/compact". So to make it works I suggest to use:
if(strpos($func->getImage(),'compact'))

I will make a pull request for it.

This comment has been minimized.

Copy link
@rakeshtembhurne

rakeshtembhurne Jan 29, 2013

I am building an app using CakePHP 2.2. $func->getImage() returns a string "__". Using strpos() might not fix the problem.

foreach ($func->findChildrenOfType('Literal') as $literal) {
$this->_collectLiteral($literal);
}
}
}
}

/**
Expand All @@ -157,6 +164,22 @@ private function collectVariable(PHP_PMD_Node_ASTNode $node)
$this->images[$node->getImage()][] = $node;
}

/**
* Stores the given literal node in an internal list of found variables.
*
* @param PHP_PMD_Node_ASTNode $node The context variable node.
*
* @return void
*/
private function _collectLiteral(PHP_PMD_Node_ASTNode $node)
{
$variable = '$' . trim($node->getImage(), '\'');
if (!isset($this->_images[$variable])) {
$this->_images[$variable] = array();
}
$this->_images[$variable][] = $node;
}

/**
* Template method that performs the real node image check.
*
Expand Down
21 changes: 21 additions & 0 deletions src/test/php/PHP/PMD/Rule/UnusedLocalVariableTest.php
Expand Up @@ -487,4 +487,25 @@ public function testRuleDoesNotApplyToCatchStatement()
$rule->setReport($this->getReportMock(0));
$rule->apply($this->getMethod());
}

/**
* testRuleDoesNotApplyToCatchStatement
*
* <code>
* class Foo {
* public function bar() {
* $key = 'ok';
* return compact('key');
* }
* }
* </code>
*
* @return void
*/
public function testRuleDoesNotApplyToCompactFunction()
{
$rule = new PHP_PMD_Rule_UnusedLocalVariable();
$rule->setReport($this->getReportMock(0));
$rule->apply($this->getMethod());
}
}
@@ -0,0 +1,10 @@
<?php
class testRuleDoesNotApplyToCompactFunction
{
public function testRuleDoesNotApplyToCompactFunction()
{
$key = 'ok';
return compact('key');
}
}
?>

0 comments on commit e478912

Please sign in to comment.