• 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

97.92
/src/Standards/Squiz/Sniffs/ControlStructures/SwitchDeclarationSniff.php
1
<?php
2
/**
3
 * Enforces switch statement formatting.
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\Squiz\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
     * The number of spaces code should be indented.
21
     *
22
     * @var integer
23
     */
24
    public $indent = 4;
25

26

27
    /**
28
     * Returns an array of tokens this test wants to listen for.
29
     *
30
     * @return array<int|string>
31
     */
32
    public function register()
3✔
33
    {
34
        return [T_SWITCH];
3✔
35
    }
36

37

38
    /**
39
     * Processes this test, when one of its tokens is encountered.
40
     *
41
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
42
     * @param int                         $stackPtr  The position of the current token in the
43
     *                                               stack passed in $tokens.
44
     *
45
     * @return void
46
     */
47
    public function process(File $phpcsFile, int $stackPtr)
3✔
48
    {
49
        $tokens = $phpcsFile->getTokens();
3✔
50

51
        // We can't process SWITCH statements unless we know where they start and end.
52
        if (isset($tokens[$stackPtr]['scope_opener']) === false
3✔
53
            || isset($tokens[$stackPtr]['scope_closer']) === false
3✔
54
        ) {
UNCOV
55
            return;
×
56
        }
57

58
        $switch        = $tokens[$stackPtr];
3✔
59
        $nextCase      = $stackPtr;
3✔
60
        $caseAlignment = ($switch['column'] + $this->indent);
3✔
61
        $caseCount     = 0;
3✔
62
        $foundDefault  = false;
3✔
63

64
        while (($nextCase = $phpcsFile->findNext([T_CASE, T_DEFAULT, T_SWITCH], ($nextCase + 1), $switch['scope_closer'])) !== false) {
3✔
65
            // Skip nested SWITCH statements; they are handled on their own.
66
            if ($tokens[$nextCase]['code'] === T_SWITCH) {
3✔
67
                $nextCase = $tokens[$nextCase]['scope_closer'];
3✔
68
                continue;
3✔
69
            }
70

71
            if ($tokens[$nextCase]['code'] === T_DEFAULT) {
3✔
72
                $type         = 'Default';
3✔
73
                $foundDefault = true;
3✔
74
            } else {
75
                $type = 'Case';
3✔
76
                $caseCount++;
3✔
77
            }
78

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

87
                $fix = $phpcsFile->addFixableError($error, $nextCase, $type . 'NotLower', $data);
3✔
88
                if ($fix === true) {
3✔
89
                    $phpcsFile->fixer->replaceToken($nextCase, $expected);
3✔
90
                }
91
            }
92

93
            if ($tokens[$nextCase]['column'] !== $caseAlignment) {
3✔
94
                $error = strtoupper($type) . ' keyword must be indented ' . $this->indent . ' spaces from SWITCH keyword';
3✔
95
                $fix   = $phpcsFile->addFixableError($error, $nextCase, $type . 'Indent');
3✔
96

97
                if ($fix === true) {
3✔
98
                    $padding = str_repeat(' ', ($caseAlignment - 1));
3✔
99
                    if ($tokens[$nextCase]['column'] === 1
3✔
100
                        || $tokens[($nextCase - 1)]['code'] !== T_WHITESPACE
3✔
101
                    ) {
102
                        $phpcsFile->fixer->addContentBefore($nextCase, $padding);
3✔
103
                    } else {
UNCOV
104
                        $phpcsFile->fixer->replaceToken(($nextCase - 1), $padding);
×
105
                    }
106
                }
107
            }
108

109
            if ($type === 'Case'
3✔
110
                && ($tokens[($nextCase + 1)]['type'] !== 'T_WHITESPACE'
3✔
111
                || $tokens[($nextCase + 1)]['content'] !== ' ')
3✔
112
            ) {
113
                $error = 'CASE keyword must be followed by a single space';
3✔
114
                $fix   = $phpcsFile->addFixableError($error, $nextCase, 'SpacingAfterCase');
3✔
115
                if ($fix === true) {
3✔
116
                    if ($tokens[($nextCase + 1)]['type'] !== 'T_WHITESPACE') {
3✔
117
                        $phpcsFile->fixer->addContent($nextCase, ' ');
3✔
118
                    } else {
119
                        $phpcsFile->fixer->replaceToken(($nextCase + 1), ' ');
3✔
120
                    }
121
                }
122
            }
123

124
            if (isset($tokens[$nextCase]['scope_opener']) === false) {
3✔
125
                // Parse error or live coding.
UNCOV
126
                continue;
×
127
            }
128

129
            $opener = $tokens[$nextCase]['scope_opener'];
3✔
130
            if ($tokens[($opener - 1)]['type'] === 'T_WHITESPACE') {
3✔
131
                $error = 'There must be no space before the colon in a ' . strtoupper($type) . ' statement';
3✔
132
                $fix   = $phpcsFile->addFixableError($error, $nextCase, 'SpaceBeforeColon' . $type);
3✔
133
                if ($fix === true) {
3✔
134
                    $phpcsFile->fixer->replaceToken(($opener - 1), '');
3✔
135
                }
136
            }
137

138
            $nextBreak = $tokens[$nextCase]['scope_closer'];
3✔
139
            if ($tokens[$nextBreak]['code'] === T_BREAK
3✔
140
                || $tokens[$nextBreak]['code'] === T_RETURN
3✔
141
                || $tokens[$nextBreak]['code'] === T_CONTINUE
3✔
142
                || $tokens[$nextBreak]['code'] === T_THROW
3✔
143
                || $tokens[$nextBreak]['code'] === T_EXIT
3✔
144
                || $tokens[$nextBreak]['code'] === T_GOTO
3✔
145
            ) {
146
                if ($tokens[$nextBreak]['scope_condition'] === $nextCase) {
3✔
147
                    // Only need to check a couple of things once, even if the
148
                    // break is shared between multiple case statements, or even
149
                    // the default case.
150
                    if ($tokens[$nextBreak]['column'] !== $caseAlignment) {
3✔
151
                        $error = 'Case breaking statement must be indented ' . $this->indent . ' spaces from SWITCH keyword';
3✔
152
                        $fix   = $phpcsFile->addFixableError($error, $nextBreak, 'BreakIndent');
3✔
153

154
                        if ($fix === true) {
3✔
155
                            $padding = str_repeat(' ', ($caseAlignment - 1));
3✔
156
                            if ($tokens[$nextBreak]['column'] === 1
3✔
157
                                || $tokens[($nextBreak - 1)]['code'] !== T_WHITESPACE
3✔
158
                            ) {
159
                                $phpcsFile->fixer->addContentBefore($nextBreak, $padding);
3✔
160
                            } else {
161
                                $phpcsFile->fixer->replaceToken(($nextBreak - 1), $padding);
3✔
162
                            }
163
                        }
164
                    }
165

166
                    $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($nextBreak - 1), $stackPtr, true);
3✔
167
                    if ($tokens[$prev]['line'] !== ($tokens[$nextBreak]['line'] - 1)) {
3✔
168
                        $error = 'Blank lines are not allowed before case breaking statements';
3✔
169
                        $phpcsFile->addError($error, $nextBreak, 'SpacingBeforeBreak');
3✔
170
                    }
171

172
                    $nextLine  = $tokens[$tokens[$stackPtr]['scope_closer']]['line'];
3✔
173
                    $semicolon = $phpcsFile->findEndOfStatement($nextBreak);
3✔
174
                    for ($i = ($semicolon + 1); $i < $tokens[$stackPtr]['scope_closer']; $i++) {
3✔
175
                        if ($tokens[$i]['type'] !== 'T_WHITESPACE') {
3✔
176
                            $nextLine = $tokens[$i]['line'];
3✔
177
                            break;
3✔
178
                        }
179
                    }
180

181
                    if ($type === 'Case') {
3✔
182
                        // Ensure the BREAK statement is followed by
183
                        // a single blank line, or the end switch brace.
184
                        if ($nextLine !== ($tokens[$semicolon]['line'] + 2) && $i !== $tokens[$stackPtr]['scope_closer']) {
3✔
185
                            $error = 'Case breaking statements must be followed by a single blank line';
3✔
186
                            $fix   = $phpcsFile->addFixableError($error, $nextBreak, 'SpacingAfterBreak');
3✔
187
                            if ($fix === true) {
3✔
188
                                $phpcsFile->fixer->beginChangeset();
3✔
189
                                for ($i = ($semicolon + 1); $i <= $tokens[$stackPtr]['scope_closer']; $i++) {
3✔
190
                                    if ($tokens[$i]['line'] === $nextLine) {
3✔
191
                                        $phpcsFile->fixer->addNewlineBefore($i);
3✔
192
                                        break;
3✔
193
                                    }
194

195
                                    if ($tokens[$i]['line'] === $tokens[$semicolon]['line']) {
3✔
196
                                        continue;
3✔
197
                                    }
198

199
                                    $phpcsFile->fixer->replaceToken($i, '');
3✔
200
                                }
201

202
                                $phpcsFile->fixer->endChangeset();
3✔
203
                            }
204
                        }//end if
205
                    } else {
206
                        // Ensure the BREAK statement is not followed by a blank line.
207
                        if ($nextLine !== ($tokens[$semicolon]['line'] + 1)) {
3✔
208
                            $error = 'Blank lines are not allowed after the DEFAULT case\'s breaking statement';
3✔
209
                            $phpcsFile->addError($error, $nextBreak, 'SpacingAfterDefaultBreak');
3✔
210
                        }
211
                    }//end if
212

213
                    $caseLine = $tokens[$nextCase]['line'];
3✔
214
                    $nextLine = $tokens[$nextBreak]['line'];
3✔
215
                    for ($i = ($opener + 1); $i < $nextBreak; $i++) {
3✔
216
                        if ($tokens[$i]['type'] !== 'T_WHITESPACE') {
3✔
217
                            $nextLine = $tokens[$i]['line'];
3✔
218
                            break;
3✔
219
                        }
220
                    }
221

222
                    if ($nextLine !== ($caseLine + 1)) {
3✔
223
                        $error = 'Blank lines are not allowed after ' . strtoupper($type) . ' statements';
3✔
224
                        $phpcsFile->addError($error, $nextCase, 'SpacingAfter' . $type);
3✔
225
                    }
226
                }//end if
227

228
                if ($tokens[$nextBreak]['code'] === T_BREAK) {
3✔
229
                    if ($type === 'Case') {
3✔
230
                        // Ensure empty CASE statements are not allowed.
231
                        // They must have some code content in them. A comment is not enough.
232
                        // But count RETURN statements as valid content if they also
233
                        // happen to close the CASE statement.
234
                        $foundContent = false;
3✔
235
                        for ($i = ($tokens[$nextCase]['scope_opener'] + 1); $i < $nextBreak; $i++) {
3✔
236
                            if ($tokens[$i]['code'] === T_CASE) {
3✔
237
                                $i = $tokens[$i]['scope_opener'];
3✔
238
                                continue;
3✔
239
                            }
240

241
                            if (isset(Tokens::EMPTY_TOKENS[$tokens[$i]['code']]) === false) {
3✔
242
                                $foundContent = true;
3✔
243
                                break;
3✔
244
                            }
245
                        }
246

247
                        if ($foundContent === false) {
3✔
248
                            $error = 'Empty CASE statements are not allowed';
3✔
249
                            $phpcsFile->addError($error, $nextCase, 'EmptyCase');
3✔
250
                        }
251
                    } else {
252
                        // Ensure empty DEFAULT statements are not allowed.
253
                        // They must (at least) have a comment describing why
254
                        // the default case is being ignored.
255
                        $foundContent = false;
3✔
256
                        for ($i = ($tokens[$nextCase]['scope_opener'] + 1); $i < $nextBreak; $i++) {
3✔
257
                            if ($tokens[$i]['type'] !== 'T_WHITESPACE') {
3✔
258
                                $foundContent = true;
3✔
259
                                break;
3✔
260
                            }
261
                        }
262

263
                        if ($foundContent === false) {
3✔
264
                            $error = 'Comment required for empty DEFAULT case';
3✔
265
                            $phpcsFile->addError($error, $nextCase, 'EmptyDefault');
3✔
266
                        }
267
                    }//end if
268
                }//end if
269
            } elseif ($type === 'Default') {
3✔
270
                $error = 'DEFAULT case must have a breaking statement';
3✔
271
                $phpcsFile->addError($error, $nextCase, 'DefaultNoBreak');
3✔
272
            }//end if
273
        }//end while
274

275
        if ($foundDefault === false) {
3✔
276
            $error = 'All SWITCH statements must contain a DEFAULT case';
3✔
277
            $phpcsFile->addError($error, $stackPtr, 'MissingDefault');
3✔
278
        }
279

280
        if ($tokens[$switch['scope_closer']]['column'] !== $switch['column']) {
3✔
281
            $error = 'Closing brace of SWITCH statement must be aligned with SWITCH keyword';
3✔
282
            $phpcsFile->addError($error, $switch['scope_closer'], 'CloseBraceAlign');
3✔
283
        }
284

285
        if ($caseCount === 0) {
3✔
286
            $error = 'SWITCH statements must contain at least one CASE statement';
3✔
287
            $phpcsFile->addError($error, $stackPtr, 'MissingCase');
3✔
288
        }
289
    }
1✔
290
}
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