LinesAfterMethodSniff   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 14
c 1
b 0
f 0
dl 0
loc 39
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 3 1
A process() 0 20 6
1
<?php declare(strict_types = 1);
2
3
namespace Codor\Sniffs\Syntax;
4
5
use PHP_CodeSniffer\Sniffs\Sniff as PHP_CodeSniffer_Sniff;
6
use PHP_CodeSniffer\Files\File as PHP_CodeSniffer_File;
7
8
class LinesAfterMethodSniff implements PHP_CodeSniffer_Sniff
9
{
10
11
    /**
12
     * Returns the token types that this sniff is interested in.
13
     * @return array
14
     */
15
    public function register(): array
16
    {
17
        return [T_FUNCTION];
18
    }
19
20
    /**
21
     * Processes the tokens that this sniff is interested in.
22
     * @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
23
     * @param integer              $stackPtr  The position in the stack where
24
     *                                    the token was found.
25
     * @return void
26
     */
27
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
28
    {
29
        $tokens = $phpcsFile->getTokens();
30
        if (! isset($tokens[$stackPtr]['scope_closer'])) {
31
            return;
32
        }
33
34
        $endOfMethodIndex = $tokens[$stackPtr]['scope_closer'];
35
        $nextCodeLine = 0;
36
37
        for ($index=$endOfMethodIndex + 1; $index <= count($tokens); $index++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
38
            if (isset($tokens[$index]) && $tokens[$index]['type'] !== 'T_WHITESPACE') {
39
                $nextCodeLine = $tokens[$index]['line'];
40
                break;
41
            }
42
        }
43
44
        $linesBetween = $nextCodeLine - $tokens[$endOfMethodIndex]['line'] - 1;
45
        if ($linesBetween > 1) {
46
            $phpcsFile->addError("No more than 1 line after a method/function is allowed.", $stackPtr, __CLASS__);
47
        }
48
    }
49
}
50