PHP - Anonymous class breaks rule PHP:S1144

php

(Alex) #1

Description

Using anonymous class in PHP causes rule php:S1144 to report all private methods as unused, even though they are used.

Versions
Sonarqube: 7.3.0.15553
SonarPHP: 2.14.0.3569

How to reproduce

Simply add an anonymous class in PHP test class UnusedPrivateMethodCheck.php so it will look like:

   	private function f() {            // Noncompliant {{Remove this unused private "f" method.}}

		$foo = clone $this;
		$this->methodWithDefault();
		$code = '_i';
		$anonymousClass = new class(){

		};
		echo "${foo->j()}";
		return $foo->g(1)
			->h();
	}

Error observed

org.junit.ComparisonFailure: ERROR: Expect 4 issues instead of 8. In file (UnusedPrivateMethodCheckExample.php:41)
[----------------------------------------------------------------------]
[ '-' means expected but not raised, '+' means raised but not expected ]
  008: ➞private function f() {
+ 
+ 020: Noncompliant {{Remove this unused private "g" method.}}
+ 020: ➞private function g($p1) {         // OK
+ 020:                   ^ 0
+ 
+ 
+ 023: Noncompliant {{Remove this unused private "h" method.}}
+ 023: ➞private function h() {            // OK
+ 023:                   ^ 0
+ 
+ 
+ 026: Noncompliant {{Remove this unused private "_i" method.}}
+ 026: ➞private function _i() {           // OK - used in a simple string literal
+ 026:                   ^^ 0
+ 
+ 
+ 029: Noncompliant {{Remove this unused private "j" method.}}
+ 029: ➞private function j() {            // OK - used as encapsulated variable in string
+ 029:                   ^ 0
+ 

(Elena Vilchik) #4

Hey,

Thanks for reporting and nice reproducer! Ticket is created https://jira.sonarsource.com/browse/SONARPHP-853