Skip to content

Commit 44c6afb

Browse files
authored
Refactor PHPUnitVersionDetector to use runtime reflection
1 parent 202afe9 commit 44c6afb

File tree

1 file changed

+22
-18
lines changed

1 file changed

+22
-18
lines changed

src/Rules/PHPUnit/PHPUnitVersionDetector.php

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
namespace PHPStan\Rules\PHPUnit;
44

5+
use PHPStan\BetterReflection\Reflection\ReflectionClass;
56
use PHPStan\Reflection\ReflectionProvider;
67
use PHPUnit\Framework\TestCase;
8+
use ReflectionException;
79
use function dirname;
810
use function explode;
911
use function file_get_contents;
@@ -22,30 +24,32 @@ 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+
if ($file !== null) {
38+
$phpUnitRoot = dirname($file, 3);
39+
$phpUnitComposer = $phpUnitRoot . '/composer.json';
40+
if (is_file($phpUnitComposer)) {
41+
$composerJson = @file_get_contents($phpUnitComposer);
42+
if ($composerJson !== false) {
43+
$json = json_decode($composerJson, true);
44+
$version = $json['extra']['branch-alias']['dev-main'] ?? null;
45+
if ($version !== null) {
46+
$majorVersion = (int) explode('.', $version)[0];
4347
}
4448
}
4549
}
4650
}
4751

48-
return new PHPUnitVersion($majorVersion, $minorVersion);
52+
return new PHPUnitVersion($majorVersion);
4953
}
5054

5155
}

0 commit comments

Comments
 (0)