|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Codor\Sniffs\Files; |
|
4
|
|
|
|
|
5
|
|
|
use PHP_CodeSniffer_Sniff; |
|
6
|
|
|
use PHP_CodeSniffer_File; |
|
7
|
|
|
|
|
8
|
|
|
class FunctionParameterSniff implements PHP_CodeSniffer_Sniff |
|
9
|
|
|
{ |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* The maximum number of parameters a function can have. |
|
13
|
|
|
* @var integer |
|
14
|
|
|
*/ |
|
15
|
|
|
protected $maxNumberOfParameters = 3; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Returns the token types that this sniff is interested in. |
|
19
|
|
|
* @return array |
|
20
|
|
|
*/ |
|
21
|
|
|
public function register() |
|
22
|
|
|
{ |
|
23
|
|
|
return [T_FUNCTION]; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Processes the tokens that this sniff is interested in. |
|
28
|
|
|
* |
|
29
|
|
|
* @param PHP_CodeSniffer_File $phpcsFile The file where the token was found. |
|
30
|
|
|
* @param integer $stackPtr The position in the stack where |
|
31
|
|
|
* the token was found. |
|
32
|
|
|
* @return void |
|
33
|
|
|
*/ |
|
34
|
|
|
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) |
|
35
|
|
|
{ |
|
36
|
|
|
$tokens = $phpcsFile->getTokens(); |
|
37
|
|
|
$token = $tokens[$stackPtr]; |
|
38
|
|
|
|
|
39
|
|
|
// Skip function without body. |
|
40
|
|
|
if (isset($token['scope_opener']) === false) { |
|
41
|
|
|
return; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
$openParenthesisIndex = $token['parenthesis_opener']; |
|
45
|
|
|
$closedParenthesisIndex = $token['parenthesis_closer']; |
|
46
|
|
|
|
|
47
|
|
|
$numberOfParameters = 0; |
|
48
|
|
|
for ($index=$openParenthesisIndex+1; $index <= $closedParenthesisIndex; $index++) { |
|
49
|
|
|
if ($tokens[$index]['type'] == 'T_VARIABLE') { |
|
50
|
|
|
$numberOfParameters++; |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
if ($numberOfParameters > $this->maxNumberOfParameters) { |
|
55
|
|
|
$error = "Function has more than {$this->maxNumberOfParameters} parameters. Please reduce."; |
|
56
|
|
|
$phpcsFile->addError($error, $stackPtr); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
if ($numberOfParameters == $this->maxNumberOfParameters) { |
|
60
|
|
|
$warning = "Function has {$this->maxNumberOfParameters} parameters. Please reduce if possible."; |
|
61
|
|
|
$phpcsFile->addWarning($warning, $stackPtr); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|