-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathPreferBreakInsideSwitchOnlySniff.php
More file actions
72 lines (61 loc) · 1.87 KB
/
PreferBreakInsideSwitchOnlySniff.php
File metadata and controls
72 lines (61 loc) · 1.87 KB
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
<?php
/**
* Sniff: PreferBreakInsideSwitchOnlySniff.
*
* @package travelopia-coding-standards
*/
namespace Travelopia\Sniffs\PHP;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
/**
* Sniff to check if only break is used inside a switch case, and not continue.
*/
class PreferBreakInsideSwitchOnlySniff implements Sniff {
/**
* Register the sniff.
*
* @return mixed[]
*/
public function register(): array {
return [ T_CASE ];
}
/**
* Process the sniff.
*
* @param File $phpcsFile The file being processed.
* @param int $stackPtr Stack pointer.
*
* @return void
*/
public function process( File $phpcsFile, $stackPtr ): void {
// Get tokens.
$tokens = $phpcsFile->getTokens();
// Set Start and End pointers.
$searchStartPtr = $stackPtr + 1;
$caseEndPtr = $tokens[ $stackPtr ]['scope_closer'];
// Search for continue inside the case.
do {
// Find the next continue.
$continuePtr = $phpcsFile->findNext( T_CONTINUE, $searchStartPtr, $caseEndPtr + 1 );
// If continue is inside a loop, ignore it.
if ( false !== $continuePtr ) {
// Search for the loop in which the continue is present.
$loopStartPtr = $phpcsFile->findPrevious( [ T_WHILE, T_FOR, T_FOREACH, T_DO ], $continuePtr, $stackPtr );
$loopEndPtr = $tokens[ $loopStartPtr ]['scope_closer'];
// If the continue is inside a loop, ignore it.
if ( $loopStartPtr && $continuePtr > $loopStartPtr && $continuePtr < $loopEndPtr ) {
$searchStartPtr = $loopEndPtr + 1;
continue;
}
// Display warning.
$phpcsFile->addWarningOnLine(
'Use `break` or `continue x` where x is the nesting level to break out of the switch.',
$tokens[ $continuePtr ]['line'],
'UseBreakInsideSwitch'
);
// Set the search pointer to the next token.
$searchStartPtr = $continuePtr + 1;
}
} while ( false !== $continuePtr );
}
}