FunctionLengthSniff::process()   A
last analyzed

Complexity

Conditions 3
Paths 3

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.9
cc 3
nc 3
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 FunctionLengthSniff implements PHP_CodeSniffer_Sniff
9
{
10
11
    /**
12
     * The maximum number of lines a function or method
13
     * should have.
14
     * @var integer
15
     */
16
    public $maxLength = 20;
17
18
    /**
19
     * Returns the token types that this sniff is interested in.
20
     * @return array
21
     */
22
    public function register(): array
23
    {
24
        return [T_FUNCTION];
25
    }
26
27
    /**
28
     * Processes the tokens that this sniff is interested in.
29
     *
30
     * @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
31
     * @param integer              $stackPtr  The position in the stack where
32
     *                                    the token was found.
33
     * @return void
34
     */
35
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
36
    {
37
        $tokens = $phpcsFile->getTokens();
38
        $token = $tokens[$stackPtr];
39
40
        // Skip function without body.
41
        if (isset($token['scope_opener']) === false) {
42
            return;
43
        }
44
45
        $firstToken = $tokens[$token['scope_opener']];
46
        $lastToken = $tokens[$token['scope_closer']];
47
        $length = $lastToken['line'] - $firstToken['line'];
48
49
        if ($length > $this->maxLength) {
50
            $tokenType = strtolower(substr($token['type'], 2));
51
            $error = "Function is {$length} lines. Must be {$this->maxLength} lines or fewer.";
52
            $phpcsFile->addError($error, $stackPtr, sprintf('%sTooBig', ucfirst($tokenType)));
53
        }
54
    }
55
}
56