Skip to content

Commit

Permalink
SONARPHP-1535 S1172 should not raise an issue on throwaway variables (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
petertrr authored Nov 21, 2024
1 parent f2451ea commit d0f423e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ public class UnusedFunctionParametersCheck extends PHPVisitorCheck {

public static final String KEY = "S1172";
private static final String MESSAGE = "Remove the unused function parameter \"%s\".";
Deque<Boolean> hasFuncGetArgsStack = new ArrayDeque<>();
List<IdentifierTree> constructorPromotedProperties = new ArrayList<>();
private final Deque<Boolean> hasFuncGetArgsStack = new ArrayDeque<>();
private List<IdentifierTree> constructorPromotedProperties = new ArrayList<>();

@Override
public void visitFunctionCall(FunctionCallTree tree) {
Expand Down Expand Up @@ -94,7 +94,7 @@ private void checkParameters(FunctionTree tree) {
List<IdentifierTree> unused = new ArrayList<>();

for (Symbol symbol : scope.getSymbols(Symbol.Kind.PARAMETER)) {
if (symbol.usages().isEmpty() && !constructorPromotedProperties.contains(symbol.declaration())) {
if (!isExcluded(symbol) && symbol.usages().isEmpty() && !constructorPromotedProperties.contains(symbol.declaration())) {
unused.add(symbol.declaration());
}
}
Expand Down Expand Up @@ -124,4 +124,10 @@ private static boolean isExcluded(MethodDeclarationTree tree) {
|| (methodSymbol.visibility() != Visibility.PRIVATE && methodSymbol.owner().is(ClassSymbol.Kind.ABSTRACT));
}

private static boolean isExcluded(Symbol symbol) {
return symbol.name().chars()
// skip the leading '$'
.skip(1)
.allMatch(c -> '_' == c);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,13 @@ public function __construct($a) {} // Noncompliant
public function __construct(private $a, $b) {} // Noncompliant
// ^^
}

// Compliant: exclude underscore as a convention for unused variable
$x = function($p1, $_, $__) {
return $p1;
};

// Underscore as a prefix has no special meaning
$x = function($p1, $_p2, $__p3) { // Noncompliant 2
return $p1;
};

0 comments on commit d0f423e

Please sign in to comment.