Skip to content

Commit b9e5158

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

File tree

1 file changed

+25
-24
lines changed

1 file changed

+25
-24
lines changed

src/Rules/PHPUnit/PHPUnitVersionDetector.php

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22

33
namespace PHPStan\Rules\PHPUnit;
44

5-
use PHPStan\Reflection\ReflectionProvider;
65
use PHPUnit\Framework\TestCase;
6+
use ReflectionClass;
7+
use ReflectionException;
78
use function dirname;
89
use function explode;
910
use function file_get_contents;
@@ -13,33 +14,33 @@
1314
class PHPUnitVersionDetector
1415
{
1516

16-
private ReflectionProvider $reflectionProvider;
17-
18-
public function __construct(ReflectionProvider $reflectionProvider)
19-
{
20-
$this->reflectionProvider = $reflectionProvider;
21-
}
22-
2317
public function createPHPUnitVersion(): PHPUnitVersion
2418
{
19+
$file = false;
2520
$majorVersion = null;
2621
$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-
}
22+
23+
try {
24+
// uses runtime reflection to reduce unnecessary work while bootstrapping PHPStan.
25+
// static reflection would need to AST parse and build up reflection for a lot of files otherwise.
26+
$reflection = new ReflectionClass(TestCase::class);
27+
$file = $reflection->getFileName();
28+
} catch (ReflectionException $e) {
29+
// PHPUnit might not be installed
30+
}
31+
32+
if ($file !== false) {
33+
$phpUnitRoot = dirname($file, 3);
34+
$phpUnitComposer = $phpUnitRoot . '/composer.json';
35+
if (is_file($phpUnitComposer)) {
36+
$composerJson = @file_get_contents($phpUnitComposer);
37+
if ($composerJson !== false) {
38+
$json = json_decode($composerJson, true);
39+
$version = $json['extra']['branch-alias']['dev-main'] ?? null;
40+
if ($version !== null) {
41+
$versionParts = explode('.', $version);
42+
$majorVersion = (int) $versionParts[0];
43+
$minorVersion = (int) $versionParts[1];
4344
}
4445
}
4546
}

0 commit comments

Comments
 (0)