• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPCSStandards / PHP_CodeSniffer / 17663621563

12 Sep 2025 03:25AM UTC coverage: 78.786%. Remained the same
17663621563

push

github

web-flow
Merge pull request #1243 from PHPCSStandards/phpcs-4.x/feature/155-normalize-some-code-style-rules-5

CS: normalize code style rules [5]

294 of 308 new or added lines in 191 files covered. (95.45%)

2354 existing lines in 130 files now uncovered.

19732 of 25045 relevant lines covered (78.79%)

96.47 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.95
/src/Standards/PSR2/Sniffs/ControlStructures/SwitchDeclarationSniff.php
1
<?php
2
/**
3
 * Ensures all switch statements are defined correctly.
4
 *
5
 * @author    Greg Sherwood <gsherwood@squiz.net>
6
 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
7
 * @license   https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
8
 */
9

10
namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures;
11

12
use PHP_CodeSniffer\Files\File;
13
use PHP_CodeSniffer\Sniffs\Sniff;
14
use PHP_CodeSniffer\Util\Tokens;
15

16
class SwitchDeclarationSniff implements Sniff
17
{
18

19
    /**
20
     * Tokens which can terminate a "case".
21
     *
22
     * @var array<int|string, int|string>
23
     */
24
    private const CASE_TERMINATING_TOKENS = [
25
        T_RETURN   => T_RETURN,
26
        T_BREAK    => T_BREAK,
27
        T_CONTINUE => T_CONTINUE,
28
        T_THROW    => T_THROW,
29
        T_EXIT     => T_EXIT,
30
        T_GOTO     => T_GOTO,
31
    ];
32

33
    /**
34
     * The number of spaces code should be indented.
35
     *
36
     * @var integer
37
     */
38
    public $indent = 4;
39

40

41
    /**
42
     * Returns an array of tokens this test wants to listen for.
43
     *
44
     * @return array<int|string>
45
     */
46
    public function register()
3✔
47
    {
48
        return [T_SWITCH];
3✔
49
    }
50

51

52
    /**
53
     * Processes this test, when one of its tokens is encountered.
54
     *
55
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
56
     * @param int                         $stackPtr  The position of the current token in the
57
     *                                               stack passed in $tokens.
58
     *
59
     * @return void
60
     */
61
    public function process(File $phpcsFile, int $stackPtr)
3✔
62
    {
63
        $tokens = $phpcsFile->getTokens();
3✔
64

65
        // We can't process SWITCH statements unless we know where they start and end.
66
        if (isset($tokens[$stackPtr]['scope_opener']) === false
3✔
67
            || isset($tokens[$stackPtr]['scope_closer']) === false
3✔
68
        ) {
UNCOV
69
            return;
×
70
        }
71

72
        $switch        = $tokens[$stackPtr];
3✔
73
        $nextCase      = $stackPtr;
3✔
74
        $caseAlignment = ($switch['column'] + $this->indent);
3✔
75

76
        while (($nextCase = $this->findNextCase($phpcsFile, ($nextCase + 1), $switch['scope_closer'])) !== false) {
3✔
77
            if ($tokens[$nextCase]['code'] === T_DEFAULT) {
3✔
78
                $type = 'default';
3✔
79
            } else {
80
                $type = 'case';
3✔
81
            }
82

83
            if ($tokens[$nextCase]['content'] !== strtolower($tokens[$nextCase]['content'])) {
3✔
84
                $expected = strtolower($tokens[$nextCase]['content']);
3✔
85
                $error    = strtoupper($type) . ' keyword must be lowercase; expected "%s" but found "%s"';
3✔
86
                $data     = [
2✔
87
                    $expected,
3✔
88
                    $tokens[$nextCase]['content'],
3✔
89
                ];
2✔
90

91
                $fix = $phpcsFile->addFixableError($error, $nextCase, $type . 'NotLower', $data);
3✔
92
                if ($fix === true) {
3✔
93
                    $phpcsFile->fixer->replaceToken($nextCase, $expected);
3✔
94
                }
95
            }
96

97
            if ($type === 'case'
3✔
98
                && ($tokens[($nextCase + 1)]['code'] !== T_WHITESPACE
3✔
99
                || $tokens[($nextCase + 1)]['content'] !== ' ')
3✔
100
            ) {
101
                $error = 'CASE keyword must be followed by a single space';
3✔
102
                $fix   = $phpcsFile->addFixableError($error, $nextCase, 'SpacingAfterCase');
3✔
103
                if ($fix === true) {
3✔
104
                    if ($tokens[($nextCase + 1)]['code'] !== T_WHITESPACE) {
3✔
105
                        $phpcsFile->fixer->addContent($nextCase, ' ');
3✔
106
                    } else {
107
                        $phpcsFile->fixer->replaceToken(($nextCase + 1), ' ');
3✔
108
                    }
109
                }
110
            }
111

112
            $opener     = $tokens[$nextCase]['scope_opener'];
3✔
113
            $nextCloser = $tokens[$nextCase]['scope_closer'];
3✔
114
            if ($tokens[$opener]['code'] === T_COLON) {
3✔
115
                if ($tokens[($opener - 1)]['code'] === T_WHITESPACE) {
3✔
116
                    $error = 'There must be no space before the colon in a ' . strtoupper($type) . ' statement';
3✔
117
                    $fix   = $phpcsFile->addFixableError($error, $nextCase, 'SpaceBeforeColon' . strtoupper($type));
3✔
118
                    if ($fix === true) {
3✔
119
                        $phpcsFile->fixer->replaceToken(($opener - 1), '');
3✔
120
                    }
121
                }
122

123
                for ($next = ($opener + 1); $next < $nextCloser; $next++) {
3✔
124
                    if (isset(Tokens::EMPTY_TOKENS[$tokens[$next]['code']]) === false
3✔
125
                        || (isset(Tokens::COMMENT_TOKENS[$tokens[$next]['code']]) === true
3✔
126
                        && $tokens[$next]['line'] !== $tokens[$opener]['line'])
3✔
127
                    ) {
128
                        break;
3✔
129
                    }
130
                }
131

132
                if ($tokens[$next]['line'] !== ($tokens[$opener]['line'] + 1)) {
3✔
133
                    $error = 'The ' . strtoupper($type) . ' body must start on the line following the statement';
3✔
134
                    $fix   = $phpcsFile->addFixableError($error, $nextCase, 'BodyOnNextLine' . strtoupper($type));
3✔
135
                    if ($fix === true) {
3✔
136
                        if ($tokens[$next]['line'] === $tokens[$opener]['line']) {
3✔
137
                            $padding = str_repeat(' ', ($caseAlignment + $this->indent - 1));
3✔
138
                            $phpcsFile->fixer->addContentBefore($next, $phpcsFile->eolChar . $padding);
3✔
139
                        } else {
140
                            $phpcsFile->fixer->beginChangeset();
3✔
141
                            for ($i = ($opener + 1); $i < $next; $i++) {
3✔
142
                                if ($tokens[$i]['line'] === $tokens[$opener]['line']) {
3✔
143
                                    // Ignore trailing comments.
144
                                    continue;
3✔
145
                                }
146

147
                                if ($tokens[$i]['line'] === $tokens[$next]['line']) {
3✔
148
                                    break;
3✔
149
                                }
150

151
                                $phpcsFile->fixer->replaceToken($i, '');
3✔
152
                            }
153

154
                            $phpcsFile->fixer->endChangeset();
3✔
155
                        }
156
                    }//end if
157
                }//end if
158

159
                if ($tokens[$nextCloser]['scope_condition'] === $nextCase) {
3✔
160
                    // Only need to check some things once, even if the
161
                    // closer is shared between multiple case statements, or even
162
                    // the default case.
163
                    $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($nextCloser - 1), $nextCase, true);
3✔
164
                    if ($tokens[$prev]['line'] === $tokens[$nextCloser]['line']) {
3✔
165
                        $error = 'Terminating statement must be on a line by itself';
3✔
166
                        $fix   = $phpcsFile->addFixableError($error, $nextCloser, 'BreakNotNewLine');
3✔
167
                        if ($fix === true) {
3✔
168
                            $phpcsFile->fixer->addNewline($prev);
3✔
169
                            $phpcsFile->fixer->replaceToken($nextCloser, trim($tokens[$nextCloser]['content']));
3✔
170
                        }
171
                    } else {
172
                        $diff = ($tokens[$nextCase]['column'] + $this->indent - $tokens[$nextCloser]['column']);
3✔
173
                        if ($diff !== 0) {
3✔
174
                            $error = 'Terminating statement must be indented to the same level as the CASE body';
3✔
175
                            $fix   = $phpcsFile->addFixableError($error, $nextCloser, 'BreakIndent');
3✔
176
                            if ($fix === true) {
3✔
177
                                if ($diff > 0) {
3✔
178
                                    $phpcsFile->fixer->addContentBefore($nextCloser, str_repeat(' ', $diff));
3✔
179
                                } else {
180
                                    $phpcsFile->fixer->substrToken(($nextCloser - 1), 0, $diff);
3✔
181
                                }
182
                            }
183
                        }
184
                    }//end if
185
                }//end if
186
            } else {
187
                $error = strtoupper($type) . ' statements must be defined using a colon';
3✔
188
                if ($tokens[$opener]['code'] === T_SEMICOLON) {
3✔
189
                    $fix = $phpcsFile->addFixableError($error, $nextCase, 'WrongOpener' . $type);
3✔
190
                    if ($fix === true) {
3✔
191
                        $phpcsFile->fixer->replaceToken($opener, ':');
3✔
192
                    }
193
                } else {
194
                    // Probably a case/default statement with colon + curly braces.
195
                    $phpcsFile->addError($error, $nextCase, 'WrongOpener' . $type);
3✔
196
                }
197
            }//end if
198

199
            // We only want cases from here on in.
200
            if ($type !== 'case') {
3✔
201
                continue;
3✔
202
            }
203

204
            $nextCode = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), $nextCloser, true);
3✔
205

206
            if ($tokens[$nextCode]['code'] !== T_CASE && $tokens[$nextCode]['code'] !== T_DEFAULT) {
3✔
207
                // This case statement has content. If the next case or default comes
208
                // before the closer, it means we don't have an obvious terminating
209
                // statement and need to make some more effort to find one. If we
210
                // don't, we do need a comment.
211
                $nextCode = $this->findNextCase($phpcsFile, ($opener + 1), $nextCloser);
3✔
212
                if ($nextCode !== false) {
3✔
213
                    $prevCode = $phpcsFile->findPrevious(T_WHITESPACE, ($nextCode - 1), $nextCase, true);
3✔
214
                    if (isset(Tokens::COMMENT_TOKENS[$tokens[$prevCode]['code']]) === false
3✔
215
                        && $this->findNestedTerminator($phpcsFile, ($opener + 1), $nextCode) === false
3✔
216
                    ) {
217
                        $error = 'There must be a comment when fall-through is intentional in a non-empty case body';
3✔
218
                        $phpcsFile->addError($error, $nextCase, 'TerminatingComment');
3✔
219
                    }
220
                }
221
            }
222
        }//end while
223
    }
1✔
224

225

226
    /**
227
     * Find the next CASE or DEFAULT statement from a point in the file.
228
     *
229
     * Note that nested switches are ignored.
230
     *
231
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
232
     * @param int                         $stackPtr  The position to start looking at.
233
     * @param int                         $end       The position to stop looking at.
234
     *
235
     * @return int|false
236
     */
237
    private function findNextCase(File $phpcsFile, int $stackPtr, int $end)
3✔
238
    {
239
        $tokens = $phpcsFile->getTokens();
3✔
240
        while (($stackPtr = $phpcsFile->findNext([T_CASE, T_DEFAULT, T_SWITCH], $stackPtr, $end)) !== false) {
3✔
241
            // Skip nested SWITCH statements; they are handled on their own.
242
            if ($tokens[$stackPtr]['code'] === T_SWITCH) {
3✔
243
                $stackPtr = $tokens[$stackPtr]['scope_closer'];
3✔
244
                continue;
3✔
245
            }
246

247
            break;
3✔
248
        }
249

250
        return $stackPtr;
3✔
251
    }
252

253

254
    /**
255
     * Returns the position of the nested terminating statement.
256
     *
257
     * Returns false if no terminating statement was found.
258
     *
259
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
260
     * @param int                         $stackPtr  The position to start looking at.
261
     * @param int                         $end       The position to stop looking at.
262
     *
263
     * @return int|bool
264
     */
265
    private function findNestedTerminator(File $phpcsFile, int $stackPtr, int $end)
3✔
266
    {
267
        $tokens = $phpcsFile->getTokens();
3✔
268

269
        $lastToken = $phpcsFile->findPrevious(Tokens::EMPTY_TOKENS, ($end - 1), $stackPtr, true);
3✔
270
        if ($lastToken === false) {
3✔
UNCOV
271
            return false;
×
272
        }
273

274
        if ($tokens[$lastToken]['code'] === T_CLOSE_CURLY_BRACKET) {
3✔
275
            // We found a closing curly bracket and want to check if its block
276
            // belongs to a SWITCH, IF, ELSEIF or ELSE, TRY, CATCH OR FINALLY clause.
277
            // If yes, we continue searching for a terminating statement within that
278
            // block. Note that we have to make sure that every block of
279
            // the entire if/else/switch statement has a terminating statement.
280
            // For a try/catch/finally statement, either the finally block has
281
            // to have a terminating statement or every try/catch block has to have one.
282
            $currentCloser = $lastToken;
3✔
283
            $hasElseBlock  = false;
3✔
284
            $hasCatchWithoutTerminator = false;
3✔
285
            do {
286
                $scopeOpener = $tokens[$currentCloser]['scope_opener'];
3✔
287
                $scopeCloser = $tokens[$currentCloser]['scope_closer'];
3✔
288

289
                $prevToken = $phpcsFile->findPrevious(Tokens::EMPTY_TOKENS, ($scopeOpener - 1), $stackPtr, true);
3✔
290
                if ($prevToken === false) {
3✔
UNCOV
291
                    return false;
×
292
                }
293

294
                // SWITCH, IF, ELSEIF, CATCH clauses possess a condition we have to account for.
295
                if ($tokens[$prevToken]['code'] === T_CLOSE_PARENTHESIS) {
3✔
296
                    $prevToken = $tokens[$prevToken]['parenthesis_owner'];
3✔
297
                }
298

299
                if ($tokens[$prevToken]['code'] === T_IF) {
3✔
300
                    // If we have not encountered an ELSE clause by now, we cannot
301
                    // be sure that the whole statement terminates in every case.
302
                    if ($hasElseBlock === false) {
3✔
303
                        return false;
3✔
304
                    }
305

306
                    return $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser);
3✔
307
                } elseif ($tokens[$prevToken]['code'] === T_ELSEIF
3✔
308
                    || $tokens[$prevToken]['code'] === T_ELSE
3✔
309
                ) {
310
                    // If we find a terminating statement within this block,
311
                    // we continue with the previous ELSEIF or IF clause.
312
                    $hasTerminator = $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser);
3✔
313
                    if ($hasTerminator === false) {
3✔
314
                        return false;
3✔
315
                    }
316

317
                    $currentCloser = $phpcsFile->findPrevious(Tokens::EMPTY_TOKENS, ($prevToken - 1), $stackPtr, true);
3✔
318
                    if ($tokens[$prevToken]['code'] === T_ELSE) {
3✔
319
                        $hasElseBlock = true;
3✔
320
                    }
321
                } elseif ($tokens[$prevToken]['code'] === T_FINALLY) {
3✔
322
                    // If we find a terminating statement within this block,
323
                    // the whole try/catch/finally statement is covered.
324
                    $hasTerminator = $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser);
3✔
325
                    if ($hasTerminator !== false) {
3✔
326
                        return $hasTerminator;
3✔
327
                    }
328

329
                    // Otherwise, we continue with the previous TRY or CATCH clause.
330
                    $currentCloser = $phpcsFile->findPrevious(Tokens::EMPTY_TOKENS, ($prevToken - 1), $stackPtr, true);
3✔
331
                } elseif ($tokens[$prevToken]['code'] === T_TRY) {
3✔
332
                    // If we've seen CATCH blocks without terminator statement and
333
                    // have not seen a FINALLY *with* a terminator statement, we
334
                    // don't even need to bother checking the TRY.
335
                    if ($hasCatchWithoutTerminator === true) {
3✔
336
                        return false;
3✔
337
                    }
338

339
                    return $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser);
3✔
340
                } elseif ($tokens[$prevToken]['code'] === T_CATCH) {
3✔
341
                    // Keep track of seen catch statements without terminating statement,
342
                    // but don't bow out yet as there may still be a FINALLY clause
343
                    // with a terminating statement before the CATCH.
344
                    $hasTerminator = $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser);
3✔
345
                    if ($hasTerminator === false) {
3✔
346
                        $hasCatchWithoutTerminator = true;
3✔
347
                    }
348

349
                    $currentCloser = $phpcsFile->findPrevious(Tokens::EMPTY_TOKENS, ($prevToken - 1), $stackPtr, true);
3✔
350
                } elseif ($tokens[$prevToken]['code'] === T_SWITCH) {
3✔
351
                    $hasDefaultBlock = false;
3✔
352
                    $endOfSwitch     = $tokens[$prevToken]['scope_closer'];
3✔
353
                    $nextCase        = $prevToken;
3✔
354

355
                    // We look for a terminating statement within every blocks.
356
                    while (($nextCase = $this->findNextCase($phpcsFile, ($nextCase + 1), $endOfSwitch)) !== false) {
3✔
357
                        if ($tokens[$nextCase]['code'] === T_DEFAULT) {
3✔
358
                            $hasDefaultBlock = true;
3✔
359
                        }
360

361
                        $opener = $tokens[$nextCase]['scope_opener'];
3✔
362

363
                        $nextCode = $phpcsFile->findNext(Tokens::EMPTY_TOKENS, ($opener + 1), $endOfSwitch, true);
3✔
364
                        if ($tokens[$nextCode]['code'] === T_CASE || $tokens[$nextCode]['code'] === T_DEFAULT) {
3✔
365
                            // This case statement has no content, so skip it.
UNCOV
366
                            continue;
×
367
                        }
368

369
                        $endOfCase = $this->findNextCase($phpcsFile, ($opener + 1), $endOfSwitch);
3✔
370
                        if ($endOfCase === false) {
3✔
371
                            $endOfCase = $endOfSwitch;
3✔
372
                        }
373

374
                        $hasTerminator = $this->findNestedTerminator($phpcsFile, ($opener + 1), $endOfCase);
3✔
375
                        if ($hasTerminator === false) {
3✔
376
                            return false;
3✔
377
                        }
378
                    }//end while
379

380
                    // If we have not encountered a DEFAULT block by now, we cannot
381
                    // be sure that the whole statement terminates in every case.
382
                    if ($hasDefaultBlock === false) {
3✔
UNCOV
383
                        return false;
×
384
                    }
385

386
                    return $hasTerminator;
3✔
387
                } else {
UNCOV
388
                    return false;
×
389
                }//end if
390
            } while ($currentCloser !== false && $tokens[$currentCloser]['code'] === T_CLOSE_CURLY_BRACKET);
3✔
391

UNCOV
392
            return true;
×
393
        } elseif ($tokens[$lastToken]['code'] === T_SEMICOLON) {
3✔
394
            // We found the last statement of the CASE. Now we want to
395
            // check whether it is a terminating one.
396
            $terminator = $phpcsFile->findStartOfStatement(($lastToken - 1));
3✔
397
            if (isset(self::CASE_TERMINATING_TOKENS[$tokens[$terminator]['code']]) === true) {
3✔
398
                return $terminator;
3✔
399
            }
400
        }//end if
401

402
        return false;
3✔
403
    }
404
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc