Skip to content

Commit 174a0a6

Browse files
committed
PSR2/SwitchDeclaration: bug fix when determining terminating statement
Trailing comments within control structures nested within a switch case would break the determination of whether or not there is a terminating statement within the nested control structure. Making the `findNestedTerminator()` method look for non-empty instead of non-whitespace tokens fixes that and shouldn't break the `TerminatingComment` check as that has it's own check whether the last token in the case statement is a comment. Includes unit tests. Fixes 3550
1 parent 154a688 commit 174a0a6

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

src/Standards/PSR2/Sniffs/ControlStructures/SwitchDeclarationSniff.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ private function findNestedTerminator($phpcsFile, $stackPtr, $end)
247247
{
248248
$tokens = $phpcsFile->getTokens();
249249

250-
$lastToken = $phpcsFile->findPrevious(T_WHITESPACE, ($end - 1), $stackPtr, true);
250+
$lastToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($end - 1), $stackPtr, true);
251251
if ($lastToken === false) {
252252
return false;
253253
}

src/Standards/PSR2/Tests/ControlStructures/SwitchDeclarationUnitTest.inc

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -511,7 +511,7 @@ switch ( $a ) {
511511
case 1:
512512
if ($a) {
513513
try {
514-
return true;
514+
return true; // Comment.
515515
} catch (MyException $e) {
516516
throw new Exception($e->getMessage());
517517
}
@@ -584,3 +584,15 @@ switch ( $a ) {
584584
$other = $code;
585585
break;
586586
}
587+
588+
// Issue 3550 - comment after terminating statement.
589+
switch (rand()) {
590+
case 1:
591+
if (rand() === 1) {
592+
break;
593+
} else {
594+
break; // comment
595+
}
596+
default:
597+
break;
598+
}

src/Standards/PSR2/Tests/ControlStructures/SwitchDeclarationUnitTest.inc.fixed

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -506,7 +506,7 @@ switch ( $a ) {
506506
case 1:
507507
if ($a) {
508508
try {
509-
return true;
509+
return true; // Comment.
510510
} catch (MyException $e) {
511511
throw new Exception($e->getMessage());
512512
}
@@ -579,3 +579,15 @@ switch ( $a ) {
579579
$other = $code;
580580
break;
581581
}
582+
583+
// Issue 3550 - comment after terminating statement.
584+
switch (rand()) {
585+
case 1:
586+
if (rand() === 1) {
587+
break;
588+
} else {
589+
break; // comment
590+
}
591+
default:
592+
break;
593+
}

0 commit comments

Comments
 (0)