|
| 1 | +<?php |
| 2 | + |
| 3 | +use PHPStan\Collectors\Collector; |
| 4 | +use PHPStan\Rules\Rule; |
| 5 | +use ShipMonk\CoverageGuard\Config; |
| 6 | +use ShipMonk\CoverageGuard\Hierarchy\ClassMethodBlock; |
| 7 | +use ShipMonk\CoverageGuard\Hierarchy\CodeBlock; |
| 8 | +use ShipMonk\CoverageGuard\Rule\CoverageError; |
| 9 | +use ShipMonk\CoverageGuard\Rule\CoverageRule; |
| 10 | +use ShipMonk\CoverageGuard\Rule\InspectionContext; |
| 11 | +use ShipMonk\PHPStan\DeadCode\Compatibility\BackwardCompatibilityChecker; |
| 12 | +use ShipMonk\PHPStan\DeadCode\Provider\MemberUsageProvider; |
| 13 | +use ShipMonk\PHPStan\DeadCode\Reflection\ReflectionHelper; |
| 14 | + |
| 15 | +$config = new Config(); |
| 16 | +$config->addRule(new class implements CoverageRule { |
| 17 | + |
| 18 | + public function inspect( |
| 19 | + CodeBlock $codeBlock, |
| 20 | + InspectionContext $context |
| 21 | + ): ?CoverageError |
| 22 | + { |
| 23 | + if (!$codeBlock instanceof ClassMethodBlock) { |
| 24 | + return null; |
| 25 | + } |
| 26 | + |
| 27 | + if ($codeBlock->getExecutableLinesCount() < 5) { |
| 28 | + return null; |
| 29 | + } |
| 30 | + |
| 31 | + $coverage = $codeBlock->getCoveragePercentage(); |
| 32 | + $classReflection = $codeBlock->getMethodReflection()->getDeclaringClass(); |
| 33 | + $requiredCoverage = $this->getRequiredCoverage($classReflection); |
| 34 | + |
| 35 | + if ($codeBlock->getCoveragePercentage() < $requiredCoverage) { |
| 36 | + return CoverageError::create("Method <white>{$codeBlock->getMethodName()}</white> requires $requiredCoverage% coverage, but has only $coverage%."); |
| 37 | + } |
| 38 | + |
| 39 | + return null; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * @param ReflectionClass<object> $classReflection |
| 44 | + */ |
| 45 | + private function getRequiredCoverage(ReflectionClass $classReflection): int |
| 46 | + { |
| 47 | + $isPoor = in_array($classReflection->getName(), [ |
| 48 | + BackwardCompatibilityChecker::class, |
| 49 | + ReflectionHelper::class, |
| 50 | + ], true); |
| 51 | + |
| 52 | + $isCore = $classReflection->implementsInterface(MemberUsageProvider::class) |
| 53 | + || $classReflection->implementsInterface(Collector::class) |
| 54 | + || $classReflection->implementsInterface(Rule::class); |
| 55 | + |
| 56 | + return match (true) { |
| 57 | + $isCore => 80, |
| 58 | + $isPoor => 20, |
| 59 | + default => 50, |
| 60 | + }; |
| 61 | + } |
| 62 | + |
| 63 | +}); |
| 64 | + |
| 65 | +return $config; |
0 commit comments