Completed
Push — master ( 5e9323...97dbcd )
by Bill
03:12 queued 01:12
created

ConstructorLoopSniff   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 1
dl 0
loc 47
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 4 1
A process() 0 20 4
1
<?php declare(strict_types = 1);
2
3
namespace Codor\Sniffs\Classes;
4
5
use PHP_CodeSniffer_Sniff;
6
use PHP_CodeSniffer_File;
7
8
class ConstructorLoopSniff implements PHP_CodeSniffer_Sniff
9
{
10
11
    /**
12
     * The loop tokens we're lookin for.
13
     * @var array
14
     */
15
    protected $loops = ['T_FOR', 'T_FOREACH', 'T_WHILE'];
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 int                  $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
        $functionNameToken = $tokens[$stackPtr + 2];
39
        $functionName      = $functionNameToken['content'];
40
        if ($functionName !== '__construct') {
41
            return;
42
        }
43
44
        $startIndex   = $token['scope_opener'];
45
        $endIndex = $token['scope_closer'];
46
47
        for ($index=$startIndex; $index <= $endIndex; $index++) {
48
            if (in_array($tokens[$index]['type'], $this->loops)) {
49
                $phpcsFile->addError("Class constructor cannot contain a loop.", $stackPtr);
50
                continue;
51
            }
52
        }
53
    }
54
}
55