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

NewInstanceSniff::process()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 8
c 1
b 0
f 1
nc 3
nop 2
dl 0
loc 12
rs 10
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