Completed
Pull Request — master (#132)
by
unknown
01:35
created

ClassNameInConstructorSniff::process()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.3222
c 0
b 0
f 0
cc 5
nc 9
nop 2
1
<?php declare(strict_types = 1);
2
3
namespace Codor\Sniffs\Classes;
4
5
use PHP_CodeSniffer\Sniffs\Sniff as PHP_CodeSniffer_Sniff;
6
use PHP_CodeSniffer\Files\File as PHP_CodeSniffer_File;
7
8
class ClassNameInConstructorSniff implements PHP_CodeSniffer_Sniff
9
{
10
    /**
11
     * Returns the token types that this sniff is interested in.
12
     * @return array
13
     */
14
    public function register(): array
15
    {
16
        return [T_CLASS];
17
    }
18
19
    /**
20
     * Processes the tokens that this sniff is interested in.
21
     *
22
     * @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
23
     * @param integer              $stackPtr  The position in the stack where the token was found.
24
     * @return void
25
     */
26
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
27
    {
28
        $classname = $phpcsFile->getTokens()[$stackPtr + 2]['content'];
29
        $constructorDocblockText = '';
30
31
        foreach ($phpcsFile->getTokens() as $token) {
32
            if (strpos($token['content'], 'constructor')) {
33
                $constructorDocblockText = explode(' ', $token['content'])[0];
34
            }
35
        }
36
37
        if ($constructorDocblockText === '') {
38
            return;
39
        }
40
41
        if ($classname !== $constructorDocblockText) {
42
            $phpcsFile->addError("Class name should match class name declaration in constructor docblock \n Class name: {$classname} \n Constructor Defined Class {$constructorDocblockText}", $stackPtr, __CLASS__);
43
        }
44
    }
45
}
46