Skip to content

Commit 5e30669

Browse files
authored
Perf: Refactor PHPUnitVersionDetector to use runtime reflection
1 parent 202afe9 commit 5e30669

File tree

1 file changed

+25
-26
lines changed

1 file changed

+25
-26
lines changed

src/Rules/PHPUnit/PHPUnitVersionDetector.php

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,45 +2,44 @@
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;
10-
use function is_file;
1111
use function json_decode;
1212

1313
class PHPUnitVersionDetector
1414
{
1515

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

0 commit comments

Comments
 (0)