Skip to content

Rule: Allow only valid continue statements inside Switch cases #1

@Takshil-Kunadia

Description

@Takshil-Kunadia

Issue:

  • There are instances where we use switches inside a loop, followed by cases whereby once the code inside the case is processed, we directly need to skip to the next iteration, thereby using continue. Although working fine, this generates the following warning from >=PHP 7.3 ref.
PHP Warning: “continue” targeting switch is equivalent to “break”. Did you mean to use “continue 2”
  • Ideally, we should use break inside switch case, followed by processing left if any.

Description:

  • We can implement a rule that ensures only valid continue statements are used within switch cases.
  • Continue should not be allowed within a switch case unless it's part of a loop in which case it is a valid continue.
  • If a continue is found inside a switch case without a loop, it should be replaced with a break statement to avoid unintended behaviour.

Example:

switch ($var) {
    case 1:
        continue; // This should trigger a warning and suggest replacing with 'break' .
        break;
        
    case 2:
        for ($i = 0; $i < 10; $i++) {
            continue; // This is valid and should be ignored by the sniff.
        }
        break;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions