Completed
Pull Request — master (#12)
by Bill
01:43
created

FunctionParameterSniff::process()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 17
nc 13
nop 2
dl 0
loc 31
rs 8.439
c 0
b 0
f 0
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
    protected $maxNumberOfParameters = 3;
12
13
    /**
14
     * Returns the token types that this sniff is interested in.
15
     * @return array
16
     */
17
    public function register()
18
    {
19
        return [T_FUNCTION];
20
    }
21
22
    /**
23
     * Processes the tokens that this sniff is interested in.
24
     *
25
     * @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
26
     * @param integer              $stackPtr  The position in the stack where
27
     *                                    the token was found.
28
     * @return void
29
     */
30
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
31
    {
32
        $tokens = $phpcsFile->getTokens();
33
        $token = $tokens[$stackPtr];
34
35
        // Skip function without body.
36
        if (isset($token['scope_opener']) === false) {
37
            return;
38
        }
39
40
        $openParenthesisIndex = $token['parenthesis_opener'];
41
        $closedParenthesisIndex = $token['parenthesis_closer'];
42
43
        $numberOfParameters = 0;
44
        for ($index=$openParenthesisIndex+1; $index <= $closedParenthesisIndex ; $index++) { 
45
            if ($tokens[$index]['type'] == 'T_VARIABLE') {
46
                $numberOfParameters++;
47
            }
48
        }
49
50
        if ($numberOfParameters > $this->maxNumberOfParameters) {
51
            $error = "Function has more than {$this->maxNumberOfParameters} parameters. Please reduce.";
52
            $phpcsFile->addError($error, $stackPtr);
53
        }
54
55
        if ($numberOfParameters == $this->maxNumberOfParameters) {
56
            $warning = "Function has {$this->maxNumberOfParameters} parameters. Please reduce if possible.";
57
            $phpcsFile->addWarning($warning, $stackPtr);
58
59
        }
60
    }
61
}
62