-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathcoverage-guard.php
More file actions
68 lines (55 loc) · 2.07 KB
/
coverage-guard.php
File metadata and controls
68 lines (55 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php declare(strict_types = 1);
use PHPStan\Collectors\Collector;
use PHPStan\Rules\Rule;
use ShipMonk\CoverageGuard\Config;
use ShipMonk\CoverageGuard\Hierarchy\ClassMethodBlock;
use ShipMonk\CoverageGuard\Hierarchy\CodeBlock;
use ShipMonk\CoverageGuard\Rule\CoverageError;
use ShipMonk\CoverageGuard\Rule\CoverageRule;
use ShipMonk\CoverageGuard\Rule\InspectionContext;
use ShipMonk\PHPStan\DeadCode\Compatibility\BackwardCompatibilityChecker;
use ShipMonk\PHPStan\DeadCode\Provider\MemberUsageProvider;
$config = new Config();
$config->addRule(new class implements CoverageRule {
public function inspect(
CodeBlock $codeBlock,
InspectionContext $context
): ?CoverageError
{
if (!$codeBlock instanceof ClassMethodBlock) {
return null;
}
if ($codeBlock->getExecutableLinesCount() < 5) {
return null;
}
$classReflection = $context->getClassReflection();
if ($classReflection === null) {
return null;
}
$coverage = $codeBlock->getCoveragePercentage();
$requiredCoverage = $this->getRequiredCoverage($classReflection, $codeBlock->getMethodName());
if ($codeBlock->getCoveragePercentage() < $requiredCoverage) {
return CoverageError::create("Method <white>{$codeBlock->getMethodName()}</white> requires $requiredCoverage% coverage, but has only $coverage%.");
}
return null;
}
/**
* @param ReflectionClass<object> $classReflection
*/
private function getRequiredCoverage(
ReflectionClass $classReflection,
string $methodName
): int
{
$isPoor = $classReflection->getName() === BackwardCompatibilityChecker::class;
$isCore = $classReflection->implementsInterface(MemberUsageProvider::class)
|| $classReflection->implementsInterface(Collector::class)
|| $classReflection->implementsInterface(Rule::class);
return match (true) {
$isPoor => 20,
$isCore => 80,
default => 50,
};
}
});
return $config;