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
|
|
|
* The forbidden strings this sniff looks for. |
12
|
|
|
* @var array |
13
|
|
|
*/ |
14
|
|
|
protected $keywords = ['And', '_and', 'Or', '_or']; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Returns the token types that this sniff is interested in. |
18
|
|
|
* @return array |
19
|
|
|
*/ |
20
|
|
|
public function register(): array |
21
|
|
|
{ |
22
|
|
|
return [T_FUNCTION]; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Processes the tokens that this sniff is interested in. |
27
|
|
|
* |
28
|
|
|
* @param PHP_CodeSniffer_File $phpcsFile The file where the token was found. |
29
|
|
|
* @param integer $stackPtr The position in the stack where |
30
|
|
|
* the token was found. |
31
|
|
|
* @return void |
32
|
|
|
*/ |
33
|
|
|
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) |
34
|
|
|
{ |
35
|
|
|
$tokens = $phpcsFile->getTokens(); |
36
|
|
|
$functionName = $tokens[$stackPtr + 2]['content']; |
37
|
|
|
$token = $tokens[$stackPtr]; |
38
|
|
|
|
39
|
|
|
$start = $token['scope_opener']; |
40
|
|
|
$end = $token['scope_closer']; |
41
|
|
|
|
42
|
|
|
foreach (range($start, $end) as $index) { |
43
|
|
|
if ($tokens[$index]['type'] === 'T_NEW') { |
44
|
|
|
$phpcsFile->addWarning($this->getWarningMessage($functionName), $tokens[$index]['line'], __CLASS__); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Gets the warning message for this sniff. |
51
|
|
|
* @return string |
52
|
|
|
*/ |
53
|
|
|
protected function getWarningMessage(string $functionName): string |
54
|
|
|
{ |
55
|
|
|
return sprintf('Function %s use new keyword - consider to use DI.', $functionName); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|