/
SwitchDeclarationSniff.php
360 lines (308 loc) · 15.5 KB
/
SwitchDeclarationSniff.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
<?php
/**
* Ensures all switch statements are defined correctly.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;
class SwitchDeclarationSniff implements Sniff
{
/**
* The number of spaces code should be indented.
*
* @var integer
*/
public $indent = 4;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return [T_SWITCH];
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// We can't process SWITCH statements unless we know where they start and end.
if (isset($tokens[$stackPtr]['scope_opener']) === false
|| isset($tokens[$stackPtr]['scope_closer']) === false
) {
return;
}
$switch = $tokens[$stackPtr];
$nextCase = $stackPtr;
$caseAlignment = ($switch['column'] + $this->indent);
while (($nextCase = $this->findNextCase($phpcsFile, ($nextCase + 1), $switch['scope_closer'])) !== false) {
if ($tokens[$nextCase]['code'] === T_DEFAULT) {
$type = 'default';
} else {
$type = 'case';
}
if ($tokens[$nextCase]['content'] !== strtolower($tokens[$nextCase]['content'])) {
$expected = strtolower($tokens[$nextCase]['content']);
$error = strtoupper($type).' keyword must be lowercase; expected "%s" but found "%s"';
$data = [
$expected,
$tokens[$nextCase]['content'],
];
$fix = $phpcsFile->addFixableError($error, $nextCase, $type.'NotLower', $data);
if ($fix === true) {
$phpcsFile->fixer->replaceToken($nextCase, $expected);
}
}
if ($type === 'case'
&& ($tokens[($nextCase + 1)]['code'] !== T_WHITESPACE
|| $tokens[($nextCase + 1)]['content'] !== ' ')
) {
$error = 'CASE keyword must be followed by a single space';
$fix = $phpcsFile->addFixableError($error, $nextCase, 'SpacingAfterCase');
if ($fix === true) {
if ($tokens[($nextCase + 1)]['code'] !== T_WHITESPACE) {
$phpcsFile->fixer->addContent($nextCase, ' ');
} else {
$phpcsFile->fixer->replaceToken(($nextCase + 1), ' ');
}
}
}
$opener = $tokens[$nextCase]['scope_opener'];
$nextCloser = $tokens[$nextCase]['scope_closer'];
if ($tokens[$opener]['code'] === T_COLON) {
if ($tokens[($opener - 1)]['code'] === T_WHITESPACE) {
$error = 'There must be no space before the colon in a '.strtoupper($type).' statement';
$fix = $phpcsFile->addFixableError($error, $nextCase, 'SpaceBeforeColon'.strtoupper($type));
if ($fix === true) {
$phpcsFile->fixer->replaceToken(($opener - 1), '');
}
}
$next = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), null, true);
if ($tokens[$next]['line'] === $tokens[$opener]['line']
&& ($tokens[$next]['code'] === T_COMMENT
|| isset(Tokens::$phpcsCommentTokens[$tokens[$next]['code']]) === true)
) {
// Skip comments on the same line.
$next = $phpcsFile->findNext(T_WHITESPACE, ($next + 1), null, true);
}
if ($tokens[$next]['line'] !== ($tokens[$opener]['line'] + 1)) {
$error = 'The '.strtoupper($type).' body must start on the line following the statement';
$fix = $phpcsFile->addFixableError($error, $nextCase, 'BodyOnNextLine'.strtoupper($type));
if ($fix === true) {
if ($tokens[$next]['line'] === $tokens[$opener]['line']) {
$padding = str_repeat(' ', ($caseAlignment + $this->indent - 1));
$phpcsFile->fixer->addContentBefore($next, $phpcsFile->eolChar.$padding);
} else {
$phpcsFile->fixer->beginChangeset();
for ($i = ($opener + 1); $i < $next; $i++) {
if ($tokens[$i]['line'] === $tokens[$next]['line']) {
break;
}
$phpcsFile->fixer->replaceToken($i, '');
}
$phpcsFile->fixer->addNewLineBefore($i);
$phpcsFile->fixer->endChangeset();
}
}
}//end if
if ($tokens[$nextCloser]['scope_condition'] === $nextCase) {
// Only need to check some things once, even if the
// closer is shared between multiple case statements, or even
// the default case.
$prev = $phpcsFile->findPrevious(T_WHITESPACE, ($nextCloser - 1), $nextCase, true);
if ($tokens[$prev]['line'] === $tokens[$nextCloser]['line']) {
$error = 'Terminating statement must be on a line by itself';
$fix = $phpcsFile->addFixableError($error, $nextCloser, 'BreakNotNewLine');
if ($fix === true) {
$phpcsFile->fixer->addNewLine($prev);
$phpcsFile->fixer->replaceToken($nextCloser, trim($tokens[$nextCloser]['content']));
}
} else {
$diff = ($tokens[$nextCase]['column'] + $this->indent - $tokens[$nextCloser]['column']);
if ($diff !== 0) {
$error = 'Terminating statement must be indented to the same level as the CASE body';
$fix = $phpcsFile->addFixableError($error, $nextCloser, 'BreakIndent');
if ($fix === true) {
if ($diff > 0) {
$phpcsFile->fixer->addContentBefore($nextCloser, str_repeat(' ', $diff));
} else {
$phpcsFile->fixer->substrToken(($nextCloser - 1), 0, $diff);
}
}
}
}//end if
}//end if
} else {
$error = strtoupper($type).' statements must be defined using a colon';
$phpcsFile->addError($error, $nextCase, 'WrongOpener'.$type);
}//end if
// We only want cases from here on in.
if ($type !== 'case') {
continue;
}
$nextCode = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), $nextCloser, true);
if ($tokens[$nextCode]['code'] !== T_CASE && $tokens[$nextCode]['code'] !== T_DEFAULT) {
// This case statement has content. If the next case or default comes
// before the closer, it means we don't have an obvious terminating
// statement and need to make some more effort to find one. If we
// don't, we do need a comment.
$nextCode = $this->findNextCase($phpcsFile, ($opener + 1), $nextCloser);
if ($nextCode !== false) {
$prevCode = $phpcsFile->findPrevious(T_WHITESPACE, ($nextCode - 1), $nextCase, true);
if (isset(Tokens::$commentTokens[$tokens[$prevCode]['code']]) === false
&& $this->findNestedTerminator($phpcsFile, ($opener + 1), $nextCode) === false
) {
$error = 'There must be a comment when fall-through is intentional in a non-empty case body';
$phpcsFile->addError($error, $nextCase, 'TerminatingComment');
}
}
}
}//end while
}//end process()
/**
* Find the next CASE or DEFAULT statement from a point in the file.
*
* Note that nested switches are ignored.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param int $stackPtr The position to start looking at.
* @param int $end The position to stop looking at.
*
* @return int|false
*/
private function findNextCase($phpcsFile, $stackPtr, $end)
{
$tokens = $phpcsFile->getTokens();
while (($stackPtr = $phpcsFile->findNext([T_CASE, T_DEFAULT, T_SWITCH], $stackPtr, $end)) !== false) {
// Skip nested SWITCH statements; they are handled on their own.
if ($tokens[$stackPtr]['code'] === T_SWITCH) {
$stackPtr = $tokens[$stackPtr]['scope_closer'];
continue;
}
break;
}
return $stackPtr;
}//end findNextCase()
/**
* Returns the position of the nested terminating statement.
*
* Returns false if no terminating statement was found.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param int $stackPtr The position to start looking at.
* @param int $end The position to stop looking at.
*
* @return int|false
*/
private function findNestedTerminator($phpcsFile, $stackPtr, $end)
{
$tokens = $phpcsFile->getTokens();
$lastToken = $phpcsFile->findPrevious(T_WHITESPACE, ($end - 1), $stackPtr, true);
if ($lastToken === false) {
return false;
}
if ($tokens[$lastToken]['code'] === T_CLOSE_CURLY_BRACKET) {
// We found a closing curly bracket and want to check if its block
// belongs to a SWITCH, IF, ELSEIF or ELSE clause. If yes, we
// continue searching for a terminating statement within that
// block. Note that we have to make sure that every block of
// the entire if/else/switch statement has a terminating statement.
$currentCloser = $lastToken;
$hasElseBlock = false;
do {
$scopeOpener = $tokens[$currentCloser]['scope_opener'];
$scopeCloser = $tokens[$currentCloser]['scope_closer'];
$prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($scopeOpener - 1), $stackPtr, true);
if ($prevToken === false) {
return false;
}
// SWITCH, IF and ELSEIF clauses possess a condition we have to account for.
if ($tokens[$prevToken]['code'] === T_CLOSE_PARENTHESIS) {
$prevToken = $tokens[$prevToken]['parenthesis_owner'];
}
if ($tokens[$prevToken]['code'] === T_IF) {
// If we have not encountered an ELSE clause by now, we cannot
// be sure that the whole statement terminates in every case.
if ($hasElseBlock === false) {
return false;
}
return $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser);
} else if ($tokens[$prevToken]['code'] === T_ELSEIF
|| $tokens[$prevToken]['code'] === T_ELSE
) {
// If we find a terminating statement within this block,
// we continue with the previous ELSEIF or IF clause.
$hasTerminator = $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser);
if ($hasTerminator === false) {
return false;
}
$currentCloser = $phpcsFile->findPrevious(T_WHITESPACE, ($prevToken - 1), $stackPtr, true);
if ($tokens[$prevToken]['code'] === T_ELSE) {
$hasElseBlock = true;
}
} else if ($tokens[$prevToken]['code'] === T_SWITCH) {
$hasDefaultBlock = false;
$endOfSwitch = $tokens[$prevToken]['scope_closer'];
$nextCase = $prevToken;
// We look for a terminating statement within every blocks.
while (($nextCase = $this->findNextCase($phpcsFile, ($nextCase + 1), $endOfSwitch)) !== false) {
if ($tokens[$nextCase]['code'] === T_DEFAULT) {
$hasDefaultBlock = true;
}
$opener = $tokens[$nextCase]['scope_opener'];
$nextCode = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), $endOfSwitch, true);
if ($tokens[$nextCode]['code'] === T_CASE || $tokens[$nextCode]['code'] === T_DEFAULT) {
// This case statement has no content, so skip it.
continue;
}
$endOfCase = $this->findNextCase($phpcsFile, ($opener + 1), $endOfSwitch);
if ($endOfCase === false) {
$endOfCase = $endOfSwitch;
}
$hasTerminator = $this->findNestedTerminator($phpcsFile, ($opener + 1), $endOfCase);
if ($hasTerminator === false) {
return false;
}
}//end while
// If we have not encountered a DEFAULT block by now, we cannot
// be sure that the whole statement terminates in every case.
if ($hasDefaultBlock === false) {
return false;
}
return $hasTerminator;
} else {
return false;
}//end if
} while ($currentCloser !== false && $tokens[$currentCloser]['code'] === T_CLOSE_CURLY_BRACKET);
return true;
} else if ($tokens[$lastToken]['code'] === T_SEMICOLON) {
// We found the last statement of the CASE. Now we want to
// check whether it is a terminating one.
$terminators = [
T_RETURN,
T_BREAK,
T_CONTINUE,
T_THROW,
T_EXIT,
];
$terminator = $phpcsFile->findStartOfStatement(($lastToken - 1));
if (in_array($tokens[$terminator]['code'], $terminators, true) === true) {
return $terminator;
}
}//end if
return false;
}//end findNestedTerminator()
}//end class