Completed
Push — master ( 90421b...89471b )
by Дмитрий
48s
created

ArrayDuplicateKeys::getConfiguration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 9
ccs 0
cts 5
cp 0
crap 2
rs 9.6666
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Kévin Gomez https://github.com/K-Phoen <[email protected]>
4
 */
5
6
namespace PHPSA\Analyzer\Pass\Expression;
7
8
use PhpParser\Node\Expr;
9
use PhpParser\Node\Scalar;
10
use PHPSA\Analyzer\Pass;
11
use PHPSA\Context;
12
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
13
14
class ArrayDuplicateKeys implements Pass\AnalyzerPassInterface, Pass\ConfigurablePassInterface
15
{
16
    /**
17
     * @param Expr\Array_ $expr
18
     * @param Context $context
19
     * @return bool
20
     */
21 23
    public function pass(Expr\Array_ $expr, Context $context)
22
    {
23 23
        $result = false;
24 23
        $keys = [];
25
26
        /** @var Expr\ArrayItem $item */
27 23
        foreach ($expr->items as $item) {
28 9
            $compiledKey = $context->getExpressionCompiler()->compile($item->key);
29 9
            if (!$compiledKey->isTypeKnown() || !$compiledKey->isScalar() || !$compiledKey->hasValue()) {
30 7
                continue;
31
            }
32
33 2
            $key = $compiledKey->getValue();
34
35 2
            if (isset($keys[$key])) {
36 1
                $context->notice(
37 1
                    'array.duplicate_keys',
38 1
                    sprintf(
39 1
                        'Duplicate array key "%s" in array definition (previously declared in line %d).',
40 1
                        $item->key instanceof Expr\Variable ? sprintf('$%s (resolved value: "%s")', $item->key->name, $key) : $key,
41 1
                        $keys[$key]->getLine()
42 1
                    ),
43
                    $item
44 1
                );
45
46 1
                $result = true;
47 1
            }
48
49 2
            $keys[$key] = $item;
50 23
        }
51
52 23
        return $result;
53
    }
54
55
    /**
56
     * @return array
57
     */
58 1
    public function getRegister()
59
    {
60
        return [
61
            Expr\Array_::class
62 1
        ];
63
    }
64
65
    /**
66
     * @return TreeBuilder
67
     */
68
    public function getConfiguration()
69
    {
70
        $treeBuilder = new TreeBuilder();
71
        $treeBuilder->root('array.duplicate_keys')
72
            ->canBeDisabled()
73
        ;
74
75
        return $treeBuilder;
76
    }
77
}
78