Passed
Pull Request — master (#153)
by
unknown
01:59
created

NewInstanceSniff   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
eloc 11
c 2
b 1
f 1
dl 0
loc 42
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 3 1
A process() 0 12 3
A getWarningMessage() 0 3 1
1
<?php declare(strict_types = 1);
2
3
namespace Codor\Sniffs\Classes;
4
5
use PHP_CodeSniffer\Sniffs\Sniff as PHP_CodeSniffer_Sniff;
6
use PHP_CodeSniffer\Files\File as PHP_CodeSniffer_File;
7
8
class NewInstanceSniff implements PHP_CodeSniffer_Sniff
9
{
10
    /**
11
     * Returns the token types that this sniff is interested in.
12
     * @return array
13
     */
14
    public function register(): array
15
    {
16
        return [T_FUNCTION];
17
    }
18
19
    /**
20
     * Processes the tokens that this sniff is interested in.
21
     *
22
     * @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
23
     * @param integer              $stackPtr  The position in the stack where
24
     *                                    the token was found.
25
     * @return void
26
     */
27
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
28
    {
29
        $tokens = $phpcsFile->getTokens();
30
        $functionName = $tokens[$stackPtr + 2]['content'];
31
        $token = $tokens[$stackPtr];
32
     
33
        $start = $token['scope_opener'];
34
        $end = $token['scope_closer'];
35
36
        foreach (range($start, $end) as $index) {
37
            if ($tokens[$index]['type'] === 'T_NEW') {
38
                $phpcsFile->addWarning($this->getWarningMessage($functionName), $tokens[$index]['line'], __CLASS__);
39
            }
40
        }
41
    }
42
43
    /**
44
     * Gets the warning message for this sniff.
45
     * @return string
46
     */
47
    protected function getWarningMessage(string $functionName): string
48
    {
49
        return sprintf('Function %s use new keyword - consider to use DI.', $functionName);
50
    }
51
}
52