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

FunctionParameterSniff   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 10
c 0
b 0
f 0
wmc 7
lcom 1
cbo 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 4 1
B process() 0 31 6
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