Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 33 |
|
0.00% |
0 / 2 |
CRAP | |
0.00% |
0 / 1 |
ParenthesesAroundKeywordSniff | |
0.00% |
0 / 33 |
|
0.00% |
0 / 2 |
90 | |
0.00% |
0 / 1 |
register | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
2 | |||
process | |
0.00% |
0 / 24 |
|
0.00% |
0 / 1 |
72 |
1 | <?php |
2 | /** |
3 | * Sniff to warn when keywords are used as functions, such as: |
4 | * Pass: clone $obj |
5 | * Fail: clone( $obj ) |
6 | * Pass: require 'path/to/file.php'; |
7 | * Fail: require( 'path/to/file' ); |
8 | * |
9 | * Covers: |
10 | * * clone |
11 | * * require |
12 | * * require_once |
13 | * * include |
14 | * * include_once |
15 | */ |
16 | |
17 | namespace MediaWiki\Sniffs\ExtraCharacters; |
18 | |
19 | use PHP_CodeSniffer\Files\File; |
20 | use PHP_CodeSniffer\Sniffs\Sniff; |
21 | |
22 | class ParenthesesAroundKeywordSniff implements Sniff { |
23 | |
24 | /** |
25 | * @inheritDoc |
26 | */ |
27 | public function register(): array { |
28 | return [ |
29 | T_CLONE, |
30 | T_REQUIRE, |
31 | T_REQUIRE_ONCE, |
32 | T_INCLUDE, |
33 | T_INCLUDE_ONCE, |
34 | T_BREAK, |
35 | T_CONTINUE, |
36 | ]; |
37 | } |
38 | |
39 | /** |
40 | * @param File $phpcsFile |
41 | * @param int $stackPtr The current token index. |
42 | * @return void |
43 | */ |
44 | public function process( File $phpcsFile, $stackPtr ) { |
45 | $tokens = $phpcsFile->getTokens(); |
46 | |
47 | $opener = $phpcsFile->findNext( [ T_WHITESPACE ], $stackPtr + 1, null, true ); |
48 | if ( $opener === false || |
49 | $tokens[$opener]['code'] !== T_OPEN_PARENTHESIS || |
50 | !isset( $tokens[$opener]['parenthesis_closer'] ) |
51 | ) { |
52 | // not a whitespace and parenthesis after the keyword, possible a comment or live coding |
53 | return; |
54 | } |
55 | |
56 | $fix = $phpcsFile->addFixableWarning( |
57 | '%s keyword must not be used as a function.', |
58 | $opener, |
59 | 'ParenthesesAroundKeywords', |
60 | [ $tokens[$stackPtr]['content'] ] |
61 | ); |
62 | |
63 | if ( $fix ) { |
64 | $phpcsFile->fixer->beginChangeset(); |
65 | if ( $tokens[$stackPtr + 1]['code'] !== T_WHITESPACE ) { |
66 | // Ensure the both tokens are not mangled together without space |
67 | $phpcsFile->fixer->addContent( $stackPtr, ' ' ); |
68 | } |
69 | |
70 | $phpcsFile->fixer->replaceToken( $opener, '' ); |
71 | // remove whitespace after the opener |
72 | if ( $tokens[$opener + 1]['code'] === T_WHITESPACE ) { |
73 | $phpcsFile->fixer->replaceToken( $opener + 1, '' ); |
74 | } |
75 | |
76 | $closer = $tokens[$opener]['parenthesis_closer']; |
77 | $phpcsFile->fixer->replaceToken( $closer, '' ); |
78 | // remove whitespace before the closer |
79 | if ( $tokens[$closer - 1]['code'] === T_WHITESPACE ) { |
80 | $phpcsFile->fixer->replaceToken( $closer - 1, '' ); |
81 | } |
82 | $phpcsFile->fixer->endChangeset(); |
83 | } |
84 | } |
85 | } |