Skip to content

False positive from PSR2.ControlStructures.SwitchDeclaration.TerminatingComment when using trailing comment #3550

@zorac

Description

@zorac

Describe the bug
A false positive is reported if a switch case contains an if/else structure where all branches exit the switch, and one of the branches ends with a comment. Minimal example is below; the error is also reported if one or more elseif branches exist, if the comment is on a different branch, if the comment is on the line after the break statement, or if return is used in place of break. No error is reported if the comment is removed, or is on the line before the break.

Code sample

<?php

switch (rand()) {
    case 1:
        if (rand() === 1) {
            break;
        } else {
            break; // comment
        }
    default:
        break;
}

Custom ruleset

<?xml version="1.0"?>
<ruleset name="My Custom Standard">
  <rule ref="PSR2.ControlStructures.SwitchDeclaration"/>
</ruleset>

To reproduce
Steps to reproduce the behavior:

  1. Create a file called test.php with the code sample above...
  2. Run phpcs test.php ...
  3. See error message displayed
--------------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
--------------------------------------------------------------------------------
 4 | ERROR | There must be a comment when fall-through is intentional in a
   |       | non-empty case body
   |       | (PSR2.ControlStructures.SwitchDeclaration.TerminatingComment)
--------------------------------------------------------------------------------

Expected behavior
No error should be reported.

Versions:

  • OS: macOS 12.2.1
  • PHP: 8.3.1
  • PHPCS: 3.6.2
  • Standard: -

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions