diff --git a/src/Rules/Exceptions/EmptyExceptionRule.php b/src/Rules/Exceptions/EmptyExceptionRule.php index 3479e92..b1a9cf9 100644 --- a/src/Rules/Exceptions/EmptyExceptionRule.php +++ b/src/Rules/Exceptions/EmptyExceptionRule.php @@ -8,6 +8,7 @@ use PHPStan\Analyser\Scope; use PHPStan\Broker\Broker; use PHPStan\Rules\Rule; +use function strpos; class EmptyExceptionRule implements Rule { @@ -25,7 +26,7 @@ public function processNode(Node $node, Scope $scope): array { if ($this->isEmpty($node->stmts)) { return [ - 'Empty catch block' + 'Empty catch block. If you are sure this is meant to be empty, please add a "// @ignoreException" comment in the catch block.' ]; } @@ -41,6 +42,12 @@ private function isEmpty(array $stmts): bool foreach ($stmts as $stmt) { if (!$stmt instanceof Node\Stmt\Nop) { return false; + } else { + foreach ($stmt->getComments() as $comment) { + if (strpos($comment->getText(), '@ignoreException') !== false) { + return false; + } + } } } diff --git a/tests/Rules/Exceptions/EmptyExceptionRuleTest.php b/tests/Rules/Exceptions/EmptyExceptionRuleTest.php index d3a5ddd..ef2260f 100644 --- a/tests/Rules/Exceptions/EmptyExceptionRuleTest.php +++ b/tests/Rules/Exceptions/EmptyExceptionRuleTest.php @@ -16,11 +16,11 @@ public function testCheckCatchedException() { $this->analyse([__DIR__ . '/data/catch.php'], [ [ - 'Empty catch block', + 'Empty catch block. If you are sure this is meant to be empty, please add a "// @ignoreException" comment in the catch block.', 14, ], [ - 'Empty catch block', + 'Empty catch block. If you are sure this is meant to be empty, please add a "// @ignoreException" comment in the catch block.', 24, ], ]); diff --git a/tests/Rules/Exceptions/data/catch.php b/tests/Rules/Exceptions/data/catch.php index f34d711..be2fc5b 100644 --- a/tests/Rules/Exceptions/data/catch.php +++ b/tests/Rules/Exceptions/data/catch.php @@ -24,3 +24,8 @@ class MyCatchException extends \Exception } catch (\Exception $e) { // Do nothing } + +try { +} catch (\Exception $e) { + // @ignoreException +}