Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
InArrayUsageSniff
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 2
72
0.00% covered (danger)
0.00%
0 / 1
 register
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 process
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
56
1<?php
2
3namespace MediaWiki\Sniffs\Usage;
4
5use PHP_CodeSniffer\Files\File;
6use PHP_CodeSniffer\Sniffs\Sniff;
7
8/**
9 * Custom sniff that finds unnecessary slow in_array() that can be replaced with array_key_exists()
10 * or isset().
11 *
12 * @license GPL-2.0-or-later
13 * @author Thiemo Kreuz
14 */
15class InArrayUsageSniff implements Sniff {
16
17    /**
18     * @inheritDoc
19     */
20    public function register(): array {
21        return [ T_STRING ];
22    }
23
24    /**
25     * @param File $phpcsFile
26     * @param int $stackPtr
27     *
28     * @return void
29     */
30    public function process( File $phpcsFile, $stackPtr ) {
31        $tokens = $phpcsFile->getTokens();
32
33        // Continue only if the string we found is wrapped in at least one parenthesis
34        if ( !isset( $tokens[$stackPtr]['nested_parenthesis'] ) ) {
35            return;
36        }
37
38        if ( $tokens[$stackPtr]['content'] !== 'array_flip'
39            && $tokens[$stackPtr]['content'] !== 'array_keys'
40        ) {
41            return;
42        }
43
44        $openParenthesisPtr = array_key_last( $tokens[$stackPtr]['nested_parenthesis'] );
45
46        // Continue only if the parenthesis belongs to an in_array() call
47        if ( $tokens[$openParenthesisPtr - 1]['code'] !== T_STRING
48            || strcasecmp( $tokens[$openParenthesisPtr - 1]['content'], 'in_array' ) !== 0
49        ) {
50            return;
51        }
52
53        $previous = $phpcsFile->findPrevious(
54            T_WHITESPACE,
55            $stackPtr - 1,
56            $openParenthesisPtr + 1,
57            true
58        );
59        if ( $tokens[$previous]['code'] !== T_COMMA ) {
60            return;
61        }
62
63        $phpcsFile->addError(
64            'Found slow in_array( …, %s() ), should be array_key_exists() or isset()',
65            $stackPtr,
66            'Found',
67            [ $tokens[$stackPtr]['content'] ]
68        );
69    }
70}