From 010fafda172880a6d2644d5ee5a2584381afef43 Mon Sep 17 00:00:00 2001 From: Jean-Luc Herren Date: Tue, 10 Aug 2021 21:28:17 +0200 Subject: [PATCH] Generic/EmptyStatementSniff: Allow comments to be considered non-empty --- .../CodeAnalysis/EmptyStatementSniff.php | 17 +++++++++++++++-- .../CodeAnalysis/EmptyStatementUnitTest.inc | 18 ++++++++++++++++++ .../CodeAnalysis/EmptyStatementUnitTest.php | 3 +++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyStatementSniff.php b/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyStatementSniff.php index 574bb0ba5a..f4c9fc3e1b 100644 --- a/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyStatementSniff.php +++ b/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyStatementSniff.php @@ -30,6 +30,13 @@ class EmptyStatementSniff implements Sniff { + /** + * Empty statements which should not be reported when there is a comment in the body. + * + * @var string[] + */ + public $allowComment = []; + /** * Registers the tokens that this sniff wants to listen for. @@ -75,10 +82,16 @@ public function process(File $phpcsFile, $stackPtr) return; } + if (in_array(strtolower($token['content']), $this->allowComment, true) === true) { + $skipTokens = T_WHITESPACE; + } else { + $skipTokens = Tokens::$emptyTokens; + } + $next = $phpcsFile->findNext( - Tokens::$emptyTokens, + $skipTokens, ($token['scope_opener'] + 1), - ($token['scope_closer'] - 1), + $token['scope_closer'], true ); diff --git a/src/Standards/Generic/Tests/CodeAnalysis/EmptyStatementUnitTest.inc b/src/Standards/Generic/Tests/CodeAnalysis/EmptyStatementUnitTest.inc index 210788a1de..3de42a788f 100644 --- a/src/Standards/Generic/Tests/CodeAnalysis/EmptyStatementUnitTest.inc +++ b/src/Standards/Generic/Tests/CodeAnalysis/EmptyStatementUnitTest.inc @@ -72,3 +72,21 @@ try { if (true) {} elseif (false) {} match($foo) {}; + +// phpcs:set Generic.CodeAnalysis.EmptyStatement allowComment[] elseif,catch + +if ($foo) { + // Should complain here +} elseif ($bar) { + // Should not complain here +} else { + // Should complain here +} + +TRY { + // Should complain here +} CATCH (Exception $exception) { + // Should not complain here +} + +// phpcs:set Generic.CodeAnalysis.EmptyStatement allowComment[] diff --git a/src/Standards/Generic/Tests/CodeAnalysis/EmptyStatementUnitTest.php b/src/Standards/Generic/Tests/CodeAnalysis/EmptyStatementUnitTest.php index 4e00ada1ca..ebeece7d5e 100644 --- a/src/Standards/Generic/Tests/CodeAnalysis/EmptyStatementUnitTest.php +++ b/src/Standards/Generic/Tests/CodeAnalysis/EmptyStatementUnitTest.php @@ -40,6 +40,9 @@ public function getErrorList() 68 => 1, 72 => 2, 74 => 1, + 78 => 1, + 82 => 1, + 86 => 1, ]; }//end getErrorList()