FunctionParameterSniff::process()   A
last analyzed

Complexity

Conditions 5
Paths 12

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 11
c 2
b 0
f 0
dl 0
loc 18
rs 9.6111
cc 5
nc 12
nop 2
1
<?php declare(strict_types = 1);
2
3
namespace Codor\Sniffs\Files;
4
5
use PHP_CodeSniffer\Sniffs\Sniff as PHP_CodeSniffer_Sniff;
6
use PHP_CodeSniffer\Files\File as 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
    public $maxParameters = 3;
16
17
    /**
18
     * Returns the token types that this sniff is interested in.
19
     * @return array
20
     */
21
    public function register(): array
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
        $openParenIndex   = $token['parenthesis_opener'];
39
        $closedParenIndex = $token['parenthesis_closer'];
40
41
        $numberOfParameters = 0;
42
        for ($index=$openParenIndex+1; $index <= $closedParenIndex; $index++) {
43
            $tokens[$index]['type'] == 'T_VARIABLE' ? $numberOfParameters++ : null;
44
        }
45
46
        if ($numberOfParameters > $this->maxParameters) {
47
            $phpcsFile->addError("Function has more than {$this->maxParameters} parameters. Please reduce.", $stackPtr, __CLASS__ . 'MoreThan');
48
        }
49
50
        if ($numberOfParameters == $this->maxParameters) {
51
            $phpcsFile->addWarning("Function has {$this->maxParameters} parameters.", $stackPtr, __CLASS__ . 'hasMax');
52
        }
53
    }
54
}
55