RightValueSniffer   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 28
c 1
b 0
f 0
dl 0
loc 73
ccs 24
cts 24
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B sniff() 0 29 7
A __construct() 0 9 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Pluswerk\TypoScriptLinter\Sniff;
5
6
use Helmich\TypoScriptLint\Linter\Report\Issue;
7
use Helmich\TypoScriptParser\Tokenizer\Token;
8
9
final class RightValueSniffer
10
{
11
    // Default ignore patterns
12
    private const CONSTANT_EXPRESSION = '\{\$[a-zA-Z0-9_\.]+\}';
13
    private const TRUE_VALUE = '1';
14
    private const FALSE_VALUE = '0';
15
16
    /**
17
     * @var array
18
     */
19
    private $knownRightValues = [];
20
21
    /**
22
     * @var array
23
     */
24
    private $ignorePatterns = [];
25
26
    /**
27
     * @var bool
28
     */
29
    private $ignoreClassNameValues = true;
30
31
    /**
32
     * RightValueSniffer constructor.
33
     *
34
     * @param array $ignorePatterns
35
     * @param bool  $ignoreClassNameValues
36
     */
37 9
    public function __construct(array $ignorePatterns, bool $ignoreClassNameValues)
38
    {
39
        // Add constants boolean expression to ignore patterns
40 9
        $ignorePatterns[] = self::CONSTANT_EXPRESSION;
41 9
        $ignorePatterns[] = self::TRUE_VALUE;
42 9
        $ignorePatterns[] = self::FALSE_VALUE;
43
44 9
        $this->ignorePatterns = $ignorePatterns;
45 9
        $this->ignoreClassNameValues = $ignoreClassNameValues;
46 9
    }
47
48
    /**
49
     * @param Token $token
50
     *
51
     * @return Issue|null
52
     */
53 9
    public function sniff(Token $token): ?Issue
54
    {
55 9
        if ($token->getType() !== Token::TYPE_RIGHTVALUE) {
56 1
            return null;
57
        }
58
59 8
        foreach ($this->ignorePatterns as $ignorePattern) {
60 8
            if (preg_match('/' . $ignorePattern . '/', $token->getValue())) {
61 8
                return null;
62
            }
63
        }
64
65 4
        if ($this->ignoreClassNameValues && class_exists($token->getValue())) {
66 1
            return null;
67
        }
68
69 3
        if (in_array($token->getValue(), $this->knownRightValues, true)) {
70 2
            return new Issue(
71 2
                $token->getLine(),
72 2
                null,
73 2
                'Duplicated value "' . $token->getValue() . '". Consider extracting it into a constant.',
74 2
                Issue::SEVERITY_WARNING,
75 2
                __CLASS__
76
            );
77
        }
78
79 3
        $this->knownRightValues[] = $token->getValue();
80
81 3
        return null;
82
    }
83
}
84