Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 21 |
|
0.00% |
0 / 2 |
CRAP | |
0.00% |
0 / 1 |
ReferenceThisSniff | |
0.00% |
0 / 21 |
|
0.00% |
0 / 2 |
56 | |
0.00% |
0 / 1 |
register | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
2 | |||
process | |
0.00% |
0 / 18 |
|
0.00% |
0 / 1 |
42 |
1 | <?php |
2 | /** |
3 | * This program is free software; you can redistribute it and/or modify |
4 | * it under the terms of the GNU General Public License as published by |
5 | * the Free Software Foundation; either version 2 of the License, or |
6 | * (at your option) any later version. |
7 | * |
8 | * This program is distributed in the hope that it will be useful, |
9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
11 | * GNU General Public License for more details. |
12 | * |
13 | * You should have received a copy of the GNU General Public License along |
14 | * with this program; if not, write to the Free Software Foundation, Inc., |
15 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
16 | * http://www.gnu.org/copyleft/gpl.html |
17 | * |
18 | * @file |
19 | */ |
20 | |
21 | namespace MediaWiki\Sniffs\Usage; |
22 | |
23 | use PHP_CodeSniffer\Files\File; |
24 | use PHP_CodeSniffer\Sniffs\Sniff; |
25 | |
26 | /** |
27 | * Disallows usage of &$this, which results in |
28 | * warnings since PHP 7.1 |
29 | */ |
30 | class ReferenceThisSniff implements Sniff { |
31 | |
32 | /** |
33 | * @inheritDoc |
34 | */ |
35 | public function register(): array { |
36 | // As per https://www.mediawiki.org/wiki/Manual:Coding_conventions/PHP#Other |
37 | return [ |
38 | T_BITWISE_AND |
39 | ]; |
40 | } |
41 | |
42 | /** |
43 | * @param File $phpcsFile |
44 | * @param int $stackPtr The current token index. |
45 | * @return void |
46 | */ |
47 | public function process( File $phpcsFile, $stackPtr ) { |
48 | $tokens = $phpcsFile->getTokens(); |
49 | if ( !isset( $tokens[$stackPtr + 1] ) ) { |
50 | // Syntax error or live coding, bow out. |
51 | return; |
52 | } |
53 | |
54 | $next = $tokens[$stackPtr + 1]; |
55 | if ( $next['code'] === T_VARIABLE && $next['content'] === '$this' ) { |
56 | $after = $phpcsFile->findNext( T_WHITESPACE, $stackPtr + 2, null, true ); |
57 | if ( $after !== false && |
58 | in_array( |
59 | $tokens[$after]['code'], |
60 | [ T_OBJECT_OPERATOR, T_NULLSAFE_OBJECT_OPERATOR, T_OPEN_SQUARE_BRACKET, T_DOUBLE_COLON ] |
61 | ) |
62 | ) { |
63 | return; |
64 | } |
65 | $phpcsFile->addError( |
66 | 'The ampersand in "&$this" must be removed. If you plan to get back another ' . |
67 | 'instance of this class, assign $this to a temporary variable.', |
68 | $stackPtr, |
69 | 'Found' |
70 | ); |
71 | } |
72 | } |
73 | } |