/
InArrayUsageSniff.php
70 lines (59 loc) · 1.53 KB
/
InArrayUsageSniff.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
<?php
namespace MediaWiki\Sniffs\Usage;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
/**
* Custom sniff that finds unnecessary slow in_array() that can be replaced with array_key_exists()
* or isset().
*
* @license GPL-2.0-or-later
* @author Thiemo Kreuz
*/
class InArrayUsageSniff implements Sniff {
/**
* @inheritDoc
*/
public function register(): array {
return [ T_STRING ];
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return void
*/
public function process( File $phpcsFile, $stackPtr ) {
$tokens = $phpcsFile->getTokens();
// Continue only if the string we found is wrapped in at least one parenthesis
if ( !isset( $tokens[$stackPtr]['nested_parenthesis'] ) ) {
return;
}
if ( $tokens[$stackPtr]['content'] !== 'array_flip'
&& $tokens[$stackPtr]['content'] !== 'array_keys'
) {
return;
}
$openParenthesisPtr = array_key_last( $tokens[$stackPtr]['nested_parenthesis'] );
// Continue only if the parenthesis belongs to an in_array() call
if ( $tokens[$openParenthesisPtr - 1]['code'] !== T_STRING
|| strcasecmp( $tokens[$openParenthesisPtr - 1]['content'], 'in_array' ) !== 0
) {
return;
}
$previous = $phpcsFile->findPrevious(
T_WHITESPACE,
$stackPtr - 1,
$openParenthesisPtr + 1,
true
);
if ( $tokens[$previous]['code'] !== T_COMMA ) {
return;
}
$phpcsFile->addError(
'Found slow in_array( …, %s() ), should be array_key_exists() or isset()',
$stackPtr,
'Found',
[ $tokens[$stackPtr]['content'] ]
);
}
}