Completed
Push — master ( 4546de...186509 )
by Bill
8s
created

FunctionLengthSniff::process()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 12
nc 3
nop 2
1
<?php
2
3
namespace Codor\Sniffs\Files;
4
5
use PHP_CodeSniffer_Sniff;
6
use PHP_CodeSniffer_File;
7
8
class FunctionLengthSniff implements PHP_CodeSniffer_Sniff
9
{
10
11
    protected $maxLength = 20;
12
13
    public function register()
14
    {
15
        return [T_FUNCTION];
16
    }
17
18
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
19
    {
20
        $tokens = $phpcsFile->getTokens();
21
        $token = $tokens[$stackPtr];
22
23
        // Skip function without body.
24
        if (isset($token['scope_opener']) === false) {
25
            return 0;
26
        }
27
28
        $firstToken = $tokens[$token['scope_opener']];
29
        $lastToken = $tokens[$token['scope_closer']];
30
        $length = $lastToken['line'] - $firstToken['line'];
31
32
        if ($length > $this->maxLength) {
33
            $tokenType = strtolower(substr($token['type'], 2));
34
            $error = "Function is {$length} lines. Must be {$this->maxLength} lines or fewer.";
35
            $phpcsFile->addError($error, $stackPtr, sprintf('%sTooBig', ucfirst($tokenType)));
36
        }
37
    }
38
}
39