Php_codesniffer: "Code after RETURN statement cannot be executed" false positive when used with Switch

Created on 14 Jun 2017  路  2Comments  路  Source: squizlabs/PHP_CodeSniffer

When a return exists in a switch statement the error: 'Code after RETURN statement cannot be executed' is thrown, despite there being multiple pathways for the script to take.

switch( $something ) {
    case 'A':
        return 'A';
        break; // <- This is the nonExecutable & unreachable code the sniff refers to.
    case 'B':
        // ... etc
}
Awaiting Feedback

Most helpful comment

Well, it's not false positive, it's actually true - you can't reach it. According to PSR2 return may replace break.

|

All 2 comments

Well, it's not false positive, it's actually true - you can't reach it. According to PSR2 return may replace break.

|

Exactly what @kubawerlos said.

It was quite a while ago that PHPCS learnt that return/exit etc were valid closing statements for CASE blocks. Before that, it asked you to always include a break even if you were returning or exiting. But that created code that could never be executed, so PHPCS was changed.

In your example, the break wont be reached because the return will end execution of the block. Is this the actual code you are checking or is it a simplified example that doesn't show the exact problem?

Was this page helpful?
0 / 5 - 0 ratings