Skip to content

Commit 5ebdadc

Browse files
staabmclaude
andauthored
Support #[DataProviderClosure] in the type checking rule (#370)
* Support DataProviderClosure in the type checking rule * Don't mix up DataProviderClosure in traits with closures of the using class While analysing a trait in the context of the using class, the scope file is the class file. Lines of a trait closure were therefore compared with closures of test methods in the class file, reporting errors against an unrelated test method. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * address feedback * Kill escaped mutants of validateArgumentCount type check Cover a validateArgumentCount value which is maybe false (bool) and a falsy non-false value (null): both keep the argument count validation enabled. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f161708 commit 5ebdadc

7 files changed

Lines changed: 442 additions & 18 deletions

‎src/Rules/PHPUnit/DataProviderDataRule.php‎

Lines changed: 93 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@
33
namespace PHPStan\Rules\PHPUnit;
44

55
use PhpParser\Node;
6+
use PHPStan\Analyser\NodeCallbackInvoker;
67
use PHPStan\Analyser\Scope;
78
use PHPStan\BetterReflection\Reflection\ReflectionMethod;
89
use PHPStan\Node\Expr\TypeExpr;
10+
use PHPStan\Reflection\ClassReflection;
911
use PHPStan\Rules\MultipleNodeTypesRule;
1012
use PHPStan\Type\ObjectType;
1113
use PHPStan\Type\Type;
@@ -57,20 +59,33 @@ public function processNode(Node $node, Scope $scope): array
5759
return [];
5860
}
5961

60-
if ($scope->getFunction() === null) {
62+
$classReflection = $scope->getClassReflection();
63+
if ($classReflection === null) {
6164
return [];
6265
}
63-
if ($scope->isInAnonymousFunction()) {
66+
67+
$method = $scope->getFunction();
68+
if ($method === null) {
69+
$testMethodWithProviderClosure = $this->findTestMethodWithDataProviderClosure($node, $scope, $classReflection);
70+
if ($testMethodWithProviderClosure === null) {
71+
return [];
72+
}
73+
74+
[$testMethod, $validateArgumentCount] = $testMethodWithProviderClosure;
75+
$this->checkDataProviderData(
76+
$node,
77+
$scope,
78+
$classReflection,
79+
[[$testMethod, !$validateArgumentCount && !$testMethod->isVariadic()]],
80+
);
81+
6482
return [];
6583
}
66-
67-
$classReflection = $scope->getClassReflection();
68-
if ($classReflection === null) {
84+
if ($scope->isInAnonymousFunction()) {
6985
return [];
7086
}
7187

7288
$testWithProviderMethods = [];
73-
$method = $scope->getFunction();
7489
$testMethods = $this->testMethodsHelper->getTestMethods($classReflection, $scope);
7590
foreach ($testMethods as $testMethod) {
7691
foreach ($this->dataProviderHelper->getDataProviderMethods($scope, $testMethod, $classReflection) as [, $providerMethodName]) {
@@ -85,39 +100,100 @@ public function processNode(Node $node, Scope $scope): array
85100
return [];
86101
}
87102

103+
$maxNumberOfParameters = $this->getMaxNumberOfParameters($testWithProviderMethods);
104+
105+
$testMethodsToCheck = [];
106+
foreach ($testWithProviderMethods as $testWithProviderMethod) {
107+
$testMethodsToCheck[] = [
108+
$testWithProviderMethod,
109+
!$testWithProviderMethod->isVariadic()
110+
&& $testWithProviderMethod->getNumberOfParameters() !== $maxNumberOfParameters,
111+
];
112+
}
113+
114+
$this->checkDataProviderData($node, $scope, $classReflection, $testMethodsToCheck);
115+
116+
return [];
117+
}
118+
119+
/**
120+
* @param Node\Stmt\Return_|Node\Expr\Yield_|Node\Expr\YieldFrom $node
121+
* @param Scope&NodeCallbackInvoker $scope
122+
* @param list<array{ReflectionMethod, bool}> $testMethods test methods with a flag whether to trim arguments to the number of parameters
123+
*/
124+
private function checkDataProviderData(Node $node, Scope $scope, ClassReflection $classReflection, array $testMethods): void
125+
{
88126
$arraysTypes = $this->buildArrayTypesFromNode($node, $scope);
89127
if ($arraysTypes === []) {
90-
return [];
128+
return;
91129
}
92130

93-
$maxNumberOfParameters = $this->getMaxNumberOfParameters($testWithProviderMethods);
94-
95-
foreach ($testWithProviderMethods as $testWithProviderMethod) {
96-
$numberOfParameters = $testWithProviderMethod->getNumberOfParameters();
131+
foreach ($testMethods as [$testMethod, $trimArgs]) {
132+
$numberOfParameters = $testMethod->getNumberOfParameters();
97133

98134
foreach ($arraysTypes as [$startLine, $arraysType]) {
99135
$args = $this->arrayItemsToArgs($arraysType, $numberOfParameters);
100136
if ($args === null) {
101137
continue;
102138
}
103139

104-
if (
105-
!$testWithProviderMethod->isVariadic()
106-
&& $numberOfParameters !== $maxNumberOfParameters
107-
) {
140+
if ($trimArgs) {
108141
$args = array_slice($args, 0, $numberOfParameters);
109142
}
110143

111144
$scope->invokeNodeCallback(new Node\Expr\MethodCall(
112145
new TypeExpr(new ObjectType($classReflection->getName())),
113-
$testWithProviderMethod->getName(),
146+
$testMethod->getName(),
114147
$args,
115148
['startLine' => $startLine],
116149
));
117150
}
118151
}
152+
}
119153

120-
return [];
154+
/**
155+
* Finds the test method whose #[DataProviderClosure] attribute contains the closure
156+
* the given node is directly declared in.
157+
*
158+
* @return array{ReflectionMethod, bool}|null test method and whether the argument count should be validated
159+
*/
160+
private function findTestMethodWithDataProviderClosure(Node $node, Scope $scope, ClassReflection $classReflection): ?array
161+
{
162+
if (!$scope->isInAnonymousFunction()) {
163+
return null;
164+
}
165+
166+
// test methods declared in traits are not considered by TestMethodsHelper.
167+
// line numbers of a trait would also be compared with closures of the using class file.
168+
if ($scope->isInTrait()) {
169+
return null;
170+
}
171+
172+
// skip closures nested within the data provider closure
173+
$parentScope = $scope->getParentScope();
174+
if ($parentScope === null || $parentScope->isInAnonymousFunction()) {
175+
return null;
176+
}
177+
178+
$nodeStartPos = $node->getStartFilePos();
179+
$testMethods = $this->testMethodsHelper->getTestMethods($classReflection, $scope);
180+
foreach ($testMethods as $testMethod) {
181+
foreach ($this->dataProviderHelper->getDataProviderClosures($testMethod) as [$closure, $validateArgumentCount]) {
182+
if (
183+
$nodeStartPos < $closure->getStartFilePos()
184+
|| $nodeStartPos > $closure->getEndFilePos()
185+
) {
186+
continue;
187+
}
188+
189+
return [
190+
$testMethod,
191+
$validateArgumentCount === null || !$scope->getType($validateArgumentCount)->isFalse()->yes(),
192+
];
193+
}
194+
}
195+
196+
return null;
121197
}
122198

123199
/**

‎src/Rules/PHPUnit/DataProviderHelper.php‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
use PhpParser\Modifiers;
77
use PhpParser\Node;
88
use PhpParser\Node\Attribute;
9+
use PhpParser\Node\Expr;
910
use PhpParser\Node\Expr\ClassConstFetch;
11+
use PhpParser\Node\Expr\Closure;
1012
use PhpParser\Node\Name;
1113
use PhpParser\Node\Scalar\String_;
1214
use PhpParser\Node\Stmt\ClassLike;
@@ -75,6 +77,33 @@ public function getDataProviderMethods(
7577
yield from $this->yieldDataProviderAttributes($testMethod, $classReflection);
7678
}
7779

80+
/**
81+
* Returns closures defined via the #[DataProviderClosure] attribute (PHPUnit 13.4+)
82+
* together with the expression of its `validateArgumentCount` argument, if given.
83+
*
84+
* @return iterable<array{Closure, Expr|null}>
85+
*/
86+
public function getDataProviderClosures(ReflectionMethod $testMethod): iterable
87+
{
88+
if (!$this->PHPUnitVersion->supportsDataProviderClosureAttribute()->yes()) {
89+
return;
90+
}
91+
92+
foreach ($testMethod->getAttributesByName('PHPUnit\Framework\Attributes\DataProviderClosure') as $attr) {
93+
$args = $attr->getArgumentsExpressions();
94+
95+
$closure = $args[0] ?? $args['closure'] ?? null;
96+
if (!$closure instanceof Closure) {
97+
continue;
98+
}
99+
100+
yield [
101+
$closure,
102+
$args[1] ?? $args['validateArgumentCount'] ?? null,
103+
];
104+
}
105+
}
106+
78107
/**
79108
* @return array<PhpDocTagNode>
80109
*/

‎src/Rules/PHPUnit/PHPUnitVersion.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ public function supportsDataProviderAttribute(): TrinaryLogic
4242
return TrinaryLogic::createFromBoolean($this->majorVersion >= 10);
4343
}
4444

45+
public function supportsDataProviderClosureAttribute(): TrinaryLogic
46+
{
47+
return $this->minVersion(13, 4);
48+
}
49+
4550
public function supportsTestAttribute(): TrinaryLogic
4651
{
4752
if ($this->majorVersion === null) {

‎tests/Rules/PHPUnit/DataProviderDataRuleTest.php‎

Lines changed: 115 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,12 @@ class DataProviderDataRuleTest extends RuleTestCase
1919
{
2020
private ?int $phpunitVersion;
2121

22+
private ?int $phpunitMinorVersion = 0;
23+
2224
protected function getRule(): Rule
2325
{
2426
$reflectionProvider = $this->createReflectionProvider();
25-
$phpunitVersion = new PHPUnitVersion($this->phpunitVersion, 0);
27+
$phpunitVersion = new PHPUnitVersion($this->phpunitVersion, $this->phpunitMinorVersion);
2628

2729
/** @var list<Rule<Node>> $rules */
2830
$rules = [
@@ -298,6 +300,118 @@ public function testTrimmingArgs(): void
298300
]);
299301
}
300302

303+
public function testDataProviderClosure(): void
304+
{
305+
$this->phpunitVersion = 13;
306+
$this->phpunitMinorVersion = 4;
307+
308+
$this->analyse([__DIR__ . '/data/data-provider-closure.php'], [
309+
[
310+
'Parameter #2 $b of method DataProviderClosureTest\DataTest::testAdd() expects int, string given.',
311+
13,
312+
],
313+
[
314+
'Parameter #3 $expected of method DataProviderClosureTest\DataTest::testAdd() expects int, false given.',
315+
15,
316+
],
317+
[
318+
'Parameter #3 $expected of method DataProviderClosureTest\DataTest::testNamedDataSets() expects int, string given.',
319+
25,
320+
],
321+
[
322+
'Parameter #1 $a of method DataProviderClosureTest\DataTest::testGenerator() expects int, string given.',
323+
34,
324+
],
325+
[
326+
'Parameter #2 $b of method DataProviderClosureTest\DataTest::testGenerator() expects int, true given.',
327+
37,
328+
],
329+
[
330+
'Parameter #2 $b of method DataProviderClosureTest\DataTest::testVariables() expects int, string given.',
331+
50,
332+
],
333+
[
334+
'Parameter #2 $b of method DataProviderClosureTest\DataTest::testNamedArgument() expects int, string given.',
335+
57,
336+
],
337+
[
338+
'Method DataProviderClosureTest\DataTest::testWithArgumentCountValidation() invoked with 3 parameters, 2 required.',
339+
71,
340+
],
341+
[
342+
'Parameter #1 $a of method DataProviderClosureTest\DataTest::testWithoutArgumentCountValidationTypeError() expects int, string given.',
343+
78,
344+
],
345+
[
346+
'Parameter #2 $b of method DataProviderClosureTest\DataTest::testWithoutArgumentCountValidationTypeError() expects int, string given.',
347+
78,
348+
],
349+
[
350+
'Parameter #2 $b of method DataProviderClosureTest\DataTest::testRepeated() expects int, string given.',
351+
99,
352+
],
353+
[
354+
'Parameter #2 $b of method DataProviderClosureTest\DataTest::testSingleLine() expects int, string given.',
355+
105,
356+
],
357+
[
358+
'Parameter #3 ...$rest of method DataProviderClosureTest\DataTest::testVariadicWithoutArgumentCountValidation() expects int, string given.',
359+
111,
360+
],
361+
[
362+
'Method DataProviderClosureTest\DataTest::testConstantWithArgumentCountValidation() invoked with 3 parameters, 2 required.',
363+
129,
364+
],
365+
[
366+
'Method DataProviderClosureTest\DataTest::testSameLine() invoked with 3 parameters, 2 required.',
367+
135,
368+
],
369+
[
370+
'Method DataProviderClosureTest\DataTest::testUnknownBoolArgumentCountValidation() invoked with 3 parameters, 2 required.',
371+
142,
372+
],
373+
[
374+
'Method DataProviderClosureTest\DataTest::testFalsyArgumentCountValidation() invoked with 3 parameters, 2 required.',
375+
150,
376+
],
377+
]);
378+
}
379+
380+
public function testDataProviderClosureInTrait(): void
381+
{
382+
$this->phpunitVersion = 13;
383+
$this->phpunitMinorVersion = 4;
384+
385+
// closures of test methods declared in traits are not checked,
386+
// and must not be mixed up with closures on the same lines in the class using the trait
387+
$this->analyse([
388+
__DIR__ . '/data/data-provider-closure-trait-user.php',
389+
__DIR__ . '/data/data-provider-closure-trait.php',
390+
], []);
391+
}
392+
393+
/**
394+
* @return iterable<array{int|null, int|null}>
395+
*/
396+
static public function provideUnsupportedDataProviderClosurePHPUnitVersions(): iterable
397+
{
398+
yield [null, null];
399+
yield [12, 5];
400+
yield [13, 3];
401+
}
402+
403+
/**
404+
* @dataProvider provideUnsupportedDataProviderClosurePHPUnitVersions
405+
*/
406+
#[DataProvider('provideUnsupportedDataProviderClosurePHPUnitVersions')]
407+
public function testDataProviderClosureUnsupportedPHPUnitVersion(?int $major, ?int $minor): void
408+
{
409+
$this->phpunitVersion = $major;
410+
$this->phpunitMinorVersion = $minor;
411+
412+
$this->analyse([__DIR__ . '/data/data-provider-closure.php'], []);
413+
}
414+
301415
static public function provideNamedArgumentPHPUnitVersions(): iterable
302416
{
303417
yield [null]; // unknown phpunit version
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php // lint >= 8.5
2+
3+
namespace DataProviderClosureTraitTest;
4+
5+
use PHPUnit\Framework\Attributes\DataProviderClosure;
6+
use PHPUnit\Framework\TestCase;
7+
8+
final class TraitUserTest extends TestCase
9+
{
10+
#[DataProviderClosure(static function (): array {
11+
return [[1, 2]];
12+
})]
13+
public function testOwn(int $a, int $b): void
14+
{
15+
}
16+
17+
#[DataProviderClosure('notAClosure')]
18+
public function testNotAClosure(int $a): void
19+
{
20+
}
21+
22+
use ProviderTrait;
23+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php // lint >= 8.5
2+
3+
namespace DataProviderClosureTraitTest;
4+
5+
use PHPUnit\Framework\Attributes\DataProviderClosure;
6+
7+
trait ProviderTrait
8+
{
9+
#[DataProviderClosure(static function (): array {
10+
return [[1, 'fromTrait']];
11+
})]
12+
public function testInTrait(int $a, int $b): void
13+
{
14+
}
15+
}

0 commit comments

Comments
 (0)