Skip to content

Commit fbccba8

Browse files
committed
Name the PHPDoc tag in errors about conditional parameter types
Under bleeding edge, errors about a conditional type in @PARAM, @param-out or @param-closure-this name the tag and the parameter instead of calling it a conditional return type. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
1 parent fea0178 commit fbccba8

6 files changed

Lines changed: 166 additions & 42 deletions

File tree

‎conf/bleedingEdge.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,4 @@ parameters:
3939
checkMoreParameterCastableToStringFunctions: true
4040
checkTemplateTypeBounds: true
4141
reportTemplateInImportedTypeAlias: true
42+
checkConditionalParameterTypes: true

‎conf/config.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ parameters:
7171
checkMoreParameterCastableToStringFunctions: false
7272
checkTemplateTypeBounds: false
7373
reportTemplateInImportedTypeAlias: false
74+
checkConditionalParameterTypes: false
7475
fileExtensions:
7576
- php
7677
checkAdvancedIsset: false

‎conf/parametersSchema.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ parametersSchema:
6868
checkMoreParameterCastableToStringFunctions: bool()
6969
checkTemplateTypeBounds: bool()
7070
reportTemplateInImportedTypeAlias: bool()
71+
checkConditionalParameterTypes: bool()
7172
])
7273
fileExtensions: listOf(string())
7374
checkAdvancedIsset: bool()

‎src/Rules/PhpDoc/ConditionalReturnTypeRuleHelper.php‎

Lines changed: 43 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace PHPStan\Rules\PhpDoc;
44

5+
use PHPStan\DependencyInjection\AutowiredParameter;
56
use PHPStan\DependencyInjection\AutowiredService;
67
use PHPStan\Reflection\ExtendedParametersAcceptor;
78
use PHPStan\Rules\IdentifierRuleError;
@@ -17,65 +18,46 @@
1718
use function count;
1819
use function sprintf;
1920
use function substr;
21+
use function ucfirst;
2022

2123
#[AutowiredService]
2224
final class ConditionalReturnTypeRuleHelper
2325
{
2426

27+
public function __construct(
28+
#[AutowiredParameter(ref: '%featureToggles.checkConditionalParameterTypes%')]
29+
private bool $checkConditionalParameterTypes = false,
30+
)
31+
{
32+
}
33+
2534
/**
2635
* @return list<IdentifierRuleError>
2736
*/
2837
public function check(ExtendedParametersAcceptor $acceptor): array
2938
{
39+
/** @var list<array{ConditionalType|ConditionalTypeForParameter, string|null, string|null}> $conditionalTypes the type, the PHPDoc tag it is in, and the name of the parameter whose type it is */
3040
$conditionalTypes = [];
3141
$parametersByName = [];
3242
foreach ($acceptor->getParameters() as $parameter) {
33-
// conditional types are late-resolvable, so a type without any cannot contain one
34-
if ($parameter->getType()->hasTemplateOrLateResolvableType()) {
35-
TypeTraverser::map($parameter->getType(), static function (Type $type, callable $traverse) use (&$conditionalTypes): Type {
36-
if ($type instanceof ConditionalType || $type instanceof ConditionalTypeForParameter) {
37-
$conditionalTypes[] = $type;
38-
}
39-
40-
return $traverse($type);
41-
});
43+
$this->collectConditionalTypes($parameter->getType(), '@param', $parameter->getName(), $conditionalTypes);
44+
if ($parameter->getOutType() !== null) {
45+
$this->collectConditionalTypes($parameter->getOutType(), '@param-out', $parameter->getName(), $conditionalTypes);
4246
}
43-
44-
if ($parameter->getOutType() !== null && $parameter->getOutType()->hasTemplateOrLateResolvableType()) {
45-
TypeTraverser::map($parameter->getOutType(), static function (Type $type, callable $traverse) use (&$conditionalTypes): Type {
46-
if ($type instanceof ConditionalType || $type instanceof ConditionalTypeForParameter) {
47-
$conditionalTypes[] = $type;
48-
}
49-
50-
return $traverse($type);
51-
});
52-
}
53-
54-
if ($parameter->getClosureThisType() !== null && $parameter->getClosureThisType()->hasTemplateOrLateResolvableType()) {
55-
TypeTraverser::map($parameter->getClosureThisType(), static function (Type $type, callable $traverse) use (&$conditionalTypes): Type {
56-
if ($type instanceof ConditionalType || $type instanceof ConditionalTypeForParameter) {
57-
$conditionalTypes[] = $type;
58-
}
59-
60-
return $traverse($type);
61-
});
47+
if ($parameter->getClosureThisType() !== null) {
48+
$this->collectConditionalTypes($parameter->getClosureThisType(), '@param-closure-this', $parameter->getName(), $conditionalTypes);
6249
}
6350

6451
$parametersByName[$parameter->getName()] = $parameter;
6552
}
6653

67-
if ($acceptor->getReturnType()->hasTemplateOrLateResolvableType()) {
68-
TypeTraverser::map($acceptor->getReturnType(), static function (Type $type, callable $traverse) use (&$conditionalTypes): Type {
69-
if ($type instanceof ConditionalType || $type instanceof ConditionalTypeForParameter) {
70-
$conditionalTypes[] = $type;
71-
}
72-
73-
return $traverse($type);
74-
});
75-
}
54+
$this->collectConditionalTypes($acceptor->getReturnType(), null, null, $conditionalTypes);
7655

7756
$errors = [];
78-
foreach ($conditionalTypes as $conditionalType) {
57+
foreach ($conditionalTypes as [$conditionalType, $tagName, $tagParameterName]) {
58+
$description = $tagName === null || !$this->checkConditionalParameterTypes
59+
? 'conditional return type'
60+
: sprintf('conditional type in PHPDoc tag %s for parameter $%s', $tagName, $tagParameterName);
7961
if ($conditionalType instanceof ConditionalType) {
8062
$subjectType = $conditionalType->getSubject();
8163
if ($subjectType instanceof StaticType) {
@@ -92,15 +74,15 @@ public function check(ExtendedParametersAcceptor $acceptor): array
9274
});
9375

9476
if (count($templateTypes) === 0) {
95-
$errors[] = RuleErrorBuilder::message(sprintf('Conditional return type uses subject type %s which is not part of PHPDoc @template tags.', $subjectType->describe(VerbosityLevel::typeOnly())))
77+
$errors[] = RuleErrorBuilder::message(sprintf('%s uses subject type %s which is not part of PHPDoc @template tags.', ucfirst($description), $subjectType->describe(VerbosityLevel::typeOnly())))
9678
->identifier('conditionalType.subjectNotFound')
9779
->build();
9880
continue;
9981
}
10082
} else {
10183
$parameterName = substr($conditionalType->getParameterName(), 1);
10284
if (!array_key_exists($parameterName, $parametersByName)) {
103-
$errors[] = RuleErrorBuilder::message(sprintf('Conditional return type references unknown parameter $%s.', $parameterName))
85+
$errors[] = RuleErrorBuilder::message(sprintf('%s references unknown parameter $%s.', ucfirst($description), $parameterName))
10486
->identifier('parameter.notFound')
10587
->build();
10688
continue;
@@ -117,8 +99,9 @@ public function check(ExtendedParametersAcceptor $acceptor): array
11799
$verbosity = VerbosityLevel::getRecommendedLevelByType($subjectType, $targetType);
118100

119101
$errors[] = RuleErrorBuilder::message(sprintf(
120-
'Condition "%s" in conditional return type is always %s.',
102+
'Condition "%s" in %s is always %s.',
121103
sprintf('%s %s %s', $subjectType->describe($verbosity), $conditionalType->isNegated() ? 'is not' : 'is', $targetType->describe($verbosity)),
104+
$description,
122105
$conditionalType->isNegated()
123106
? ($isTargetSuperType->yes() ? 'false' : 'true')
124107
: ($isTargetSuperType->yes() ? 'true' : 'false'),
@@ -132,4 +115,23 @@ public function check(ExtendedParametersAcceptor $acceptor): array
132115
return $errors;
133116
}
134117

118+
/**
119+
* @param list<array{ConditionalType|ConditionalTypeForParameter, string|null, string|null}> $conditionalTypes
120+
*/
121+
private function collectConditionalTypes(Type $type, ?string $tagName, ?string $parameterName, array &$conditionalTypes): void
122+
{
123+
// conditional types are late-resolvable, so a type without any cannot contain one
124+
if (!$type->hasTemplateOrLateResolvableType()) {
125+
return;
126+
}
127+
128+
TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($tagName, $parameterName, &$conditionalTypes): Type {
129+
if ($type instanceof ConditionalType || $type instanceof ConditionalTypeForParameter) {
130+
$conditionalTypes[] = [$type, $tagName, $parameterName];
131+
}
132+
133+
return $traverse($type);
134+
});
135+
}
136+
135137
}

‎tests/PHPStan/Rules/PhpDoc/FunctionConditionalReturnTypeRuleTest.php‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,64 @@
1111
class FunctionConditionalReturnTypeRuleTest extends RuleTestCase
1212
{
1313

14+
private bool $checkConditionalParameterTypes = false;
15+
1416
protected function getRule(): Rule
1517
{
16-
return new FunctionConditionalReturnTypeRule(new ConditionalReturnTypeRuleHelper());
18+
return new FunctionConditionalReturnTypeRule(new ConditionalReturnTypeRuleHelper($this->checkConditionalParameterTypes));
19+
}
20+
21+
public function testConditionalParameterType(): void
22+
{
23+
$this->analyse([__DIR__ . '/data/conditional-parameter-type.php'], [
24+
[
25+
'Conditional return type references unknown parameter $j.',
26+
8,
27+
],
28+
[
29+
'Conditional return type uses subject type int which is not part of PHPDoc @template tags.',
30+
15,
31+
],
32+
[
33+
'Condition "int is int" in conditional return type is always true.',
34+
22,
35+
],
36+
[
37+
'Condition "int is int" in conditional return type is always true.',
38+
62,
39+
],
40+
[
41+
'Condition "int is int" in conditional return type is always true.',
42+
62,
43+
],
44+
]);
45+
}
46+
47+
public function testConditionalParameterTypeChecked(): void
48+
{
49+
$this->checkConditionalParameterTypes = true;
50+
$this->analyse([__DIR__ . '/data/conditional-parameter-type.php'], [
51+
[
52+
'Conditional type in PHPDoc tag @param for parameter $a references unknown parameter $j.',
53+
8,
54+
],
55+
[
56+
'Conditional type in PHPDoc tag @param for parameter $a uses subject type int which is not part of PHPDoc @template tags.',
57+
15,
58+
],
59+
[
60+
'Condition "int is int" in conditional type in PHPDoc tag @param for parameter $a is always true.',
61+
22,
62+
],
63+
[
64+
'Condition "int is int" in conditional return type is always true.',
65+
62,
66+
],
67+
[
68+
'Condition "int is int" in conditional type in PHPDoc tag @param for parameter $a is always true.',
69+
62,
70+
],
71+
]);
1772
}
1873

1974
public function testRule(): void
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?php
2+
3+
namespace ConditionalParameterTypeRule;
4+
5+
/**
6+
* @param ($j is int ? int : string) $a
7+
*/
8+
function unknownParameter($a): void
9+
{
10+
}
11+
12+
/**
13+
* @param (int is int ? int : string) $a
14+
*/
15+
function subjectNotTemplate($a): void
16+
{
17+
}
18+
19+
/**
20+
* @param ($i is int ? 1 : 2) $a
21+
*/
22+
function alwaysTrue(int $i, $a): void
23+
{
24+
}
25+
26+
/**
27+
* The argument decides the condition at the call site, so this is not reported.
28+
*
29+
* @param ($a is int ? int : string) $a
30+
*/
31+
function selfReference($a): void
32+
{
33+
}
34+
35+
/**
36+
* @param ($b is int ? ($a is 1 ? 1 : 2) : 3) $a
37+
*/
38+
function nestedSelfReference($a, $b): void
39+
{
40+
}
41+
42+
/**
43+
* @param ($b is int ? int : string) $a
44+
* @param ($a is int ? int : string) $b
45+
*/
46+
function cycle($a, $b): void
47+
{
48+
}
49+
50+
/**
51+
* @param int|string $a
52+
* @param-out ($a is int ? int : string) $a
53+
*/
54+
function outTypeOnTheInput(&$a): void
55+
{
56+
}
57+
58+
/**
59+
* @param ($i is int ? 1 : 2) $a
60+
* @return ($i is int ? 1 : 2)
61+
*/
62+
function alwaysTrueInBoth(int $i, $a)
63+
{
64+
}

0 commit comments

Comments
 (0)