Skip to content

Commit d82a671

Browse files
committed
SlevomatCodingStandard.Exceptions.RequireNonCapturingCatch: Fixed false positives
1 parent 923e121 commit d82a671

File tree

2 files changed

+43
-6
lines changed

2 files changed

+43
-6
lines changed

SlevomatCodingStandard/Sniffs/Exceptions/RequireNonCapturingCatchSniff.php

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@
1111
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
1212
use SlevomatCodingStandard\Helpers\TokenHelper;
1313
use SlevomatCodingStandard\Helpers\VariableHelper;
14-
use function array_keys;
1514
use function array_reverse;
1615
use function count;
1716
use function in_array;
1817
use const T_CATCH;
1918
use const T_DOUBLE_QUOTED_STRING;
19+
use const T_FINALLY;
2020
use const T_HEREDOC;
2121
use const T_VARIABLE;
2222
use const T_WHITESPACE;
@@ -76,11 +76,26 @@ public function process(File $phpcsFile, $catchPointer): void
7676

7777
$tryEndPointer = CatchHelper::getTryEndPointer($phpcsFile, $catchPointer);
7878

79-
if ($tokens[$tryEndPointer]['conditions'] !== []) {
80-
$lastConditionPointer = array_reverse(array_keys($tokens[$tryEndPointer]['conditions']))[0];
81-
$nextScopeEnd = $tokens[$lastConditionPointer]['scope_closer'];
82-
} else {
83-
$nextScopeEnd = count($tokens) - 1;
79+
$possibleFinallyPointer = $tokens[$tryEndPointer]['scope_condition'];
80+
if (
81+
$tokens[$possibleFinallyPointer]['code'] === T_FINALLY
82+
&& $this->isVariableUsedInCodePart(
83+
$phpcsFile,
84+
$tokens[$possibleFinallyPointer]['scope_opener'],
85+
$tokens[$possibleFinallyPointer]['scope_closer'],
86+
$variableName
87+
)
88+
) {
89+
return;
90+
}
91+
92+
$nextScopeEnd = count($tokens) - 1;
93+
94+
foreach (array_reverse($tokens[$tryEndPointer]['conditions'], true) as $conditionPointer => $conditionCode) {
95+
if (in_array($conditionCode, TokenHelper::$functionTokenCodes, true)) {
96+
$nextScopeEnd = $tokens[$conditionPointer]['scope_closer'];
97+
break;
98+
}
8499
}
85100

86101
if ($this->isVariableUsedInCodePart($phpcsFile, $tryEndPointer, $nextScopeEnd, $variableName)) {

tests/Sniffs/Exceptions/data/requireNonCapturingCatchNoErrors.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,25 @@ function () {
4343
}
4444

4545
};
46+
47+
function () {
48+
try {
49+
} catch (Throwable $e) {
50+
} finally {
51+
if (isset($e)) {
52+
echo $e->getMessage();
53+
}
54+
}
55+
};
56+
57+
function () {
58+
do {
59+
try {
60+
61+
} catch (\Throwable $e) {
62+
63+
}
64+
} while (true);
65+
66+
throw $e;
67+
};

0 commit comments

Comments
 (0)