Skip to content

Commit 7aae291

Browse files
committed
Refactor PHPUnitVersionDetector to use runtime reflection
1 parent 202afe9 commit 7aae291

File tree

1 file changed

+24
-18
lines changed

1 file changed

+24
-18
lines changed

src/Rules/PHPUnit/PHPUnitVersionDetector.php

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
use PHPStan\Reflection\ReflectionProvider;
66
use PHPUnit\Framework\TestCase;
7+
use ReflectionClass;
8+
use ReflectionException;
79
use function dirname;
810
use function explode;
911
use function file_get_contents;
@@ -22,30 +24,34 @@ public function __construct(ReflectionProvider $reflectionProvider)
2224

2325
public function createPHPUnitVersion(): PHPUnitVersion
2426
{
27+
$file = null;
2528
$majorVersion = null;
26-
$minorVersion = null;
27-
if ($this->reflectionProvider->hasClass(TestCase::class)) {
28-
$testCase = $this->reflectionProvider->getClass(TestCase::class);
29-
$file = $testCase->getFileName();
30-
if ($file !== null) {
31-
$phpUnitRoot = dirname($file, 3);
32-
$phpUnitComposer = $phpUnitRoot . '/composer.json';
33-
if (is_file($phpUnitComposer)) {
34-
$composerJson = @file_get_contents($phpUnitComposer);
35-
if ($composerJson !== false) {
36-
$json = json_decode($composerJson, true);
37-
$version = $json['extra']['branch-alias']['dev-main'] ?? null;
38-
if ($version !== null) {
39-
$versionParts = explode('.', $version);
40-
$majorVersion = (int) $versionParts[0];
41-
$minorVersion = (int) $versionParts[1];
42-
}
29+
30+
try {
31+
// uses runtime reflection to reduce unnecessary work while bootstrapping PHPStan.
32+
// static reflection would need to AST parse and build up reflection for a lot of files otherwise.
33+
$reflection = new ReflectionClass(TestCase::class);
34+
$file = $reflection->getFileName();
35+
} catch (ReflectionException $e) {
36+
37+
}
38+
39+
if ($file !== null) {
40+
$phpUnitRoot = dirname($file, 3);
41+
$phpUnitComposer = $phpUnitRoot . '/composer.json';
42+
if (is_file($phpUnitComposer)) {
43+
$composerJson = @file_get_contents($phpUnitComposer);
44+
if ($composerJson !== false) {
45+
$json = json_decode($composerJson, true);
46+
$version = $json['extra']['branch-alias']['dev-main'] ?? null;
47+
if ($version !== null) {
48+
$majorVersion = (int) explode('.', $version)[0];
4349
}
4450
}
4551
}
4652
}
4753

48-
return new PHPUnitVersion($majorVersion, $minorVersion);
54+
return new PHPUnitVersion($majorVersion);
4955
}
5056

5157
}

0 commit comments

Comments
 (0)