Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
PlusStringConcatSniff
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 2
56
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 / 13
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2/**
3 * Checks that plus is not used for string concat
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23namespace MediaWiki\Sniffs\Usage;
24
25use PHP_CodeSniffer\Files\File;
26use PHP_CodeSniffer\Sniffs\Sniff;
27use PHP_CodeSniffer\Util\Tokens;
28
29class PlusStringConcatSniff implements Sniff {
30
31    /**
32     * Returns an array of tokens this test wants to listen for.
33     *
34     * @return array
35     */
36    public function register(): array {
37        return [ T_PLUS, T_PLUS_EQUAL ];
38    }
39
40    /**
41     * Processes this sniff, when one of its tokens is encountered.
42     *
43     * @param File $phpcsFile The file being scanned.
44     * @param int $stackPtr The position of the current token in the stack passed in $tokens.
45     *
46     * @return void
47     */
48    public function process( File $phpcsFile, $stackPtr ) {
49        $prev = $phpcsFile->findPrevious( Tokens::$emptyTokens, $stackPtr - 1, null, true );
50        $next = $phpcsFile->findNext( Tokens::$emptyTokens, $stackPtr + 1, null, true );
51        if ( $prev === false || $next === false ) {
52            // Live coding
53            return;
54        }
55        $tokens = $phpcsFile->getTokens();
56
57        // The token + should not have a string before or after it
58        if ( isset( Tokens::$stringTokens[$tokens[$prev]['code']] )
59            || isset( Tokens::$stringTokens[$tokens[$next]['code']] )
60        ) {
61            $phpcsFile->addError(
62                'Use "%s" for string concat',
63                $stackPtr,
64                'Found',
65                [ $tokens[$stackPtr]['code'] === T_PLUS ? '.' : '.=' ]
66            );
67        }
68    }
69
70}