Skip to content

Commit 38dab46

Browse files
authored
Merge pull request #46 from nimah79/3.x
Add result caching
2 parents d9d0685 + 99d1ce6 commit 38dab46

File tree

1 file changed

+52
-2
lines changed

1 file changed

+52
-2
lines changed

src/Analyser.php

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,62 @@ public static function analyse(array $files, Closure $callback): void
2121
{
2222
$testCase = new TestCaseForTypeCoverage;
2323

24+
$cache = self::getCache();
25+
26+
$cacheIsModified = false;
2427
foreach ($files as $file) {
25-
$errors = $testCase->gatherAnalyserErrors([$file]);
26-
$ignored = $testCase->getIgnoredErrors();
28+
$fileHash = sha1_file($file);
29+
if (array_key_exists($file, $cache) && $cache[$file]['hash'] === $fileHash) {
30+
$errors = $cache[$file]['errors'];
31+
$ignored = $cache[$file]['ignored'];
32+
} else {
33+
$errors = $testCase->gatherAnalyserErrors([$file]);
34+
$ignored = $testCase->getIgnoredErrors();
35+
$cache[$file] = [
36+
'hash' => $fileHash,
37+
'errors' => $errors,
38+
'ignored' => $ignored,
39+
];
40+
$cacheIsModified = true;
41+
}
2742
$testCase->resetIgnoredErrors();
2843

2944
$callback(Result::fromPHPStanErrors($file, $errors, $ignored));
3045
}
46+
$cache = self::clearRemovedFilesFromCache($cache);
47+
if ($cacheIsModified) {
48+
self::saveCache($cache);
49+
}
50+
}
51+
52+
private static function getCache(): array
53+
{
54+
return is_file(self::getCacheFilepath())
55+
? include self::getCacheFilepath()
56+
: [];
57+
}
58+
59+
private static function saveCache(array $cache): void
60+
{
61+
file_put_contents(
62+
self::getCacheFilepath(),
63+
"<?php\nreturn ".var_export($cache, true).';',
64+
);
65+
}
66+
67+
private static function getCacheFilepath(): string
68+
{
69+
return sys_get_temp_dir().'/pest_plugin_type_coverage_cache_'.md5(__DIR__).'.php';
70+
}
71+
72+
private static function clearRemovedFilesFromCache(array $cache): array
73+
{
74+
foreach (array_keys($cache) as $file) {
75+
if (! is_file($file)) {
76+
unset($cache[$file]);
77+
}
78+
}
79+
80+
return $cache;
3181
}
3282
}

0 commit comments

Comments
 (0)