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

PHPCSStandards / PHP_CodeSniffer / 15253296250

26 May 2025 11:55AM UTC coverage: 78.632% (+0.3%) from 78.375%
15253296250

Pull #1105

github

web-flow
Merge d9441d98f into caf806050
Pull Request #1105: Skip tests when 'git' command is not available

19665 of 25009 relevant lines covered (78.63%)

88.67 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
    }//end register()
37

38

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

291
    }//end process()
1✔
292

293

294
}//end class
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc