Product and version
- SonarQube Cloud, CI-based analysis.
- Scanner:
SonarSource/sonarqube-scan-actionv7.0.0 in GitHub Actions. - PHP version of the project: 8.4.
Problem
If the first segment of a parameter type is Public, Private or Protected, the analysis cannot parse the method. The scanner logs this warning and skips the whole file:
WARN Unable to parse file [file:///.../app/Http/Controllers/FooController.php] at line 244
WARN Cannot declare parameter with visibility outside of constructor
The code is valid PHP 8. Since PHP 8.0, PHP reads a namespaced name as one token (T_NAME_QUALIFIED). Thus Private in Private\FooRepository is a namespace segment, not a visibility modifier. php -l accepts the file.
Minimal example
<?php
namespace App\Repository\Private;
class FooRepository {}
namespace App\Http;
use App\Repository\Private;
class FooController
{
public function list(Private\FooRepository $repository): void {}
}
Expected: the file is analyzed.
Actual: “Unable to parse file … Cannot declare parameter with visibility outside of constructor”, and the file gets no issues, no duplication data and no coverage.
Probable cause
In php-frontend/src/main/java/org/sonar/php/parser/PHPGrammar.java, the PARAMETER() rule is:
f.parameter(
b.zeroOrMore(ATTRIBUTE_GROUP()),
b.zeroOrMore(PROMOTION_MODIFIER()),
b.optional(DECLARED_TYPE()),
...
PROMOTION_MODIFIER() matches Private first. The rest of the name, \FooRepository, then matches DECLARED_TYPE() as a fully qualified name. After that, TreeFactory.throwOnParameterWithVisibility() finds a parameter with visibility in a method that is not __construct, and it throws the error.
SONARPHP-1085 (commit e38ac40dd5, January 2023) fixed reserved words inside namespace names for use and namespace statements. The parameter type position still has the problem.
Impact
Our code style imports repository namespaces as use App\Repository\Public; and use App\Repository\Private;, so that Public\ or Private\ stays visible at each call site. Because of this bug, the analysis skips most of our controllers: no issues, no duplication and no coverage for these files.