Skip to content

Commit 9fe6c2f

Browse files
authored
Merge pull request #474 from PHPCSStandards/utils/controlstructures-getcaughtexceptions-more-defensive-coding
ControlStructures: more defensive coding against parse errors
2 parents 437df50 + e8b37eb commit 9fe6c2f

File tree

3 files changed

+23
-6
lines changed

3 files changed

+23
-6
lines changed

PHPCSUtils/Utils/ControlStructures.php

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ public static function isElseIf(File $phpcsFile, $stackPtr)
209209
* 'type_end_token' => integer, // The stack pointer to the end of the type declaration.
210210
* )
211211
* ```
212+
* In case of an invalid catch structure, the array may be empty.
212213
*
213214
* @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified `$stackPtr` is not of
214215
* type `T_CATCH` or doesn't exist.
@@ -243,12 +244,14 @@ public static function getCaughtExceptions(File $phpcsFile, $stackPtr)
243244
}
244245

245246
if (isset(Collections::namespacedNameTokens()[$tokens[$i]['code']]) === false) {
246-
// Add the current exception to the result array.
247-
$exceptions[] = [
248-
'type' => $foundName,
249-
'type_token' => $firstToken,
250-
'type_end_token' => $lastToken,
251-
];
247+
// Add the current exception to the result array if one was found.
248+
if ($foundName !== '') {
249+
$exceptions[] = [
250+
'type' => $foundName,
251+
'type_token' => $firstToken,
252+
'type_end_token' => $lastToken,
253+
];
254+
}
252255

253256
if ($tokens[$i]['code'] === \T_BITWISE_OR) {
254257
// Multi-catch. Reset and continue.

Tests/Utils/ControlStructures/GetCaughtExceptionsTest.inc

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@ try {
3030
/* testPHP8NonCapturingCatch */
3131
} catch (RuntimeException | AnotherException) {
3232

33+
/* testMissingExceptionName */
34+
} catch ($e) {
35+
36+
/* testMultiMissingExceptionNames */
37+
} catch ( | $e) {
38+
3339
/* testLiveCoding */
3440
// Intentional parse error.
3541
} catch (

Tests/Utils/ControlStructures/GetCaughtExceptionsTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,14 @@ public function dataGetCaughtExceptions()
214214
],
215215
],
216216
],
217+
'catch-without-named-exception' => [
218+
'testMarker' => '/* testMissingExceptionName */',
219+
'expected' => [],
220+
],
221+
'multi-catch-without-named-exceptions' => [
222+
'testMarker' => '/* testMultiMissingExceptionNames */',
223+
'expected' => [],
224+
],
217225
];
218226
}
219227
}

0 commit comments

Comments
 (0)