|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Symplify\PHPStanRules\Rules; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PHPStan\Analyser\Scope; |
| 9 | +use PHPStan\DependencyInjection\NeonAdapter; |
| 10 | +use PHPStan\Node\CollectedDataNode; |
| 11 | +use PHPStan\Rules\Rule; |
| 12 | +use PHPStan\Rules\RuleErrorBuilder; |
| 13 | +use Symplify\PHPStanRules\Enum\RuleIdentifier; |
| 14 | + |
| 15 | +/** |
| 16 | + * @implements Rule<CollectedDataNode> |
| 17 | + */ |
| 18 | +final readonly class MaximumIgnoredErrorCountRule implements Rule |
| 19 | +{ |
| 20 | + /** |
| 21 | + * @var string |
| 22 | + */ |
| 23 | + public const ERROR_MESSAGE = "Ignored error count %d in phpstan.neon surpassed maximum limit %d.\nInstead of ignoring more errors, fix them to keep your codebase fit."; |
| 24 | + |
| 25 | + private NeonAdapter $neonAdapter; |
| 26 | + |
| 27 | + public function __construct( |
| 28 | + private int $limit = 0 |
| 29 | + ) { |
| 30 | + $this->neonAdapter = new NeonAdapter(); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * @return class-string<Node> |
| 35 | + */ |
| 36 | + public function getNodeType(): string |
| 37 | + { |
| 38 | + // hack to run this rule just once |
| 39 | + return CollectedDataNode::class; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * @param CollectedDataNode $node |
| 44 | + */ |
| 45 | + public function processNode(Node $node, Scope $scope): array |
| 46 | + { |
| 47 | + // not enabled yet, use " |
| 48 | + if ($this->limit === 0) { |
| 49 | + return []; |
| 50 | + } |
| 51 | + |
| 52 | + $configFilePath = getcwd() . '/phpstan.neon'; |
| 53 | + |
| 54 | + // unable to find config |
| 55 | + if (! file_exists($configFilePath)) { |
| 56 | + return []; |
| 57 | + } |
| 58 | + |
| 59 | + $phpstanNeon = $this->neonAdapter->load($configFilePath); |
| 60 | + $ignoreErrors = $phpstanNeon['parameters']['ignoreErrors'] ?? []; |
| 61 | + if (count($ignoreErrors) <= $this->limit) { |
| 62 | + return []; |
| 63 | + } |
| 64 | + |
| 65 | + $identifierRuleError = RuleErrorBuilder::message(sprintf(self::ERROR_MESSAGE, count($ignoreErrors), $this->limit)) |
| 66 | + ->identifier(RuleIdentifier::MAXIMUM_IGNORED_ERROR_COUNT) |
| 67 | + ->build(); |
| 68 | + |
| 69 | + return [$identifierRuleError]; |
| 70 | + } |
| 71 | +} |
0 commit comments