Skip to content

Commit 49cbae5

Browse files
authored
PHPUnit: Fix cross-class @dataProvider annotation not being resolved (#338)
1 parent f279267 commit 49cbae5

2 files changed

Lines changed: 28 additions & 5 deletions

File tree

src/Provider/PhpUnitUsageProvider.php

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@
1414
use ShipMonk\PHPStan\DeadCode\Graph\ClassMethodRef;
1515
use ShipMonk\PHPStan\DeadCode\Graph\ClassMethodUsage;
1616
use ShipMonk\PHPStan\DeadCode\Graph\UsageOrigin;
17-
use function array_merge;
17+
use function count;
18+
use function explode;
1819
use function is_string;
20+
use function ltrim;
1921
use function str_contains;
2022
use function str_starts_with;
2123

@@ -61,15 +63,24 @@ public function getUsages(
6163
$methodName = $method->getName();
6264

6365
$externalDataProviderMethods = $this->getExternalDataProvidersFromAttributes($method);
64-
$localDataProviderMethods = array_merge(
65-
$this->getDataProvidersFromAnnotations($method->getDocComment()),
66-
$this->getDataProvidersFromAttributes($method),
67-
);
66+
$annotationDataProviders = $this->getDataProvidersFromAnnotations($method->getDocComment());
67+
$localDataProviderMethods = $this->getDataProvidersFromAttributes($method);
6868

6969
foreach ($externalDataProviderMethods as [$externalClassName, $externalMethodName]) {
7070
$usages[] = $this->createUsage($externalClassName, $externalMethodName, "External data provider method, used by $className::$methodName");
7171
}
7272

73+
foreach ($annotationDataProviders as $dataProvider) {
74+
$parts = explode('::', $dataProvider, 2);
75+
76+
if (count($parts) === 2) {
77+
$providerClassName = ltrim($parts[0], '\\');
78+
$usages[] = $this->createUsage($providerClassName, $parts[1], "External data provider method (annotation), used by $className::$methodName");
79+
} else {
80+
$usages[] = $this->createUsage($className, $dataProvider, "Data provider method, used by $methodName");
81+
}
82+
}
83+
7384
foreach ($localDataProviderMethods as $dataProvider) {
7485
$usages[] = $this->createUsage($className, $dataProvider, "Data provider method, used by $methodName");
7586
}

tests/Rule/data/providers/phpunit.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ public static function provideTwo(): array
2525
{
2626
return [];
2727
}
28+
29+
public static function provideViaAnnotation(): array
30+
{
31+
return [];
32+
}
2833
}
2934

3035
class SomeTest extends TestCase
@@ -60,6 +65,13 @@ public function testBar(string $arg): void
6065
{
6166
}
6267

68+
/**
69+
* @dataProvider \PhpUnit\ExternalProvider::provideViaAnnotation
70+
*/
71+
public function testExternalViaAnnotation(string $arg): void
72+
{
73+
}
74+
6375
#[Test]
6476
public function someTestCase(): void
6577
{

0 commit comments

Comments
 (0)