Passed
Pull Request — master (#35)
by
unknown
03:56
created

ImportSniff   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 70
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 7 1
B process() 0 27 6
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace BestIt\Sniffs\Imports;
6
7
use PHP_CodeSniffer\Files\File;
8
use PHP_CodeSniffer\Sniffs\Sniff;
9
10
/**
11
 * Class ImportSniff.
12
 * @package BestIt\Sniffs\Imports
13
 * @author Mika Bertels <[email protected]>
14
 */
15
final class ImportSniff implements Sniff
16
{
17
    /**
18
     * Namespace separator count.
19
     *
20
     * @var int
21
     */
22
    private $nsSeperatorCount = 0;
23
24
    /**
25
     * Code when FQN is found.
26
     *
27
     * @var string
28
     */
29
    public const CODE_FQN_FOUND = 'FQNFound';
30
31
    /**
32
     * Warning message if a FQN is found.
33
     *
34
     * @var string
35
     */
36
    public const ERROR_FQN_NOT_ALLOWED = 'FQN not allowed!';
37
38
    /**
39
     * Register.
40
     *
41
     * @return int[]
42
     */
43
    public function register(): array
44
    {
45
        return [
46
            T_USE,
47
            T_NS_SEPARATOR
48
        ];
49
    }
50
51
    /**
52
     * Check if there is any FQN.
53
     *
54
     * @param File $file
55
     * @param int $position
56
     */
57
    public function process(File $file, $position): void
58
    {
59
        $tokens = $file->getTokens();
60
        $token = $tokens[$position];
61
62
        if ($token['type'] === 'T_USE') {
63
            $count = 0;
64
65
            for ($i = $position; $i <= $file->findEndOfStatement($position, [T_COMMA]); $i++) {
66
                if ($tokens[$i]['type'] === 'T_NS_SEPARATOR') {
67
                    $count++;
68
                }
69
            }
70
71
            $this->nsSeperatorCount -= $count;
72
        } elseif ($token['type'] === 'T_NS_SEPARATOR') {
73
            $this->nsSeperatorCount++;
74
        }
75
76
        if($this->nsSeperatorCount > 0){
77
            $file->addError(
78
                self::ERROR_FQN_NOT_ALLOWED,
79
                $position,
80
                self::CODE_FQN_FOUND
81
            );
82
        }
83
    }
84
}
85