Completed
Push — master ( 3708b9...fb0aff )
by Enrico
03:36
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
13
class ArrayDuplicateKeys implements Pass\AnalyzerPassInterface
14
{
15
    /**
16
     * @param Expr\Array_ $expr
17
     * @param Context $context
18
     * @return bool
19
     */
20 37
    public function pass(Expr\Array_ $expr, Context $context)
21
    {
22 37
        $result = false;
23 37
        $keys = [];
24
25
        /** @var Expr\ArrayItem $item */
26 37
        foreach ($expr->items as $item) {
27 11
            $compiledKey = $context->getExpressionCompiler()->compile($item->key);
28 11
            if (!$compiledKey->isTypeKnown() || !$compiledKey->isScalar() || !$compiledKey->hasValue()) {
29 9
                continue;
30
            }
31
32 3
            $key = $compiledKey->getValue();
33
34 3
            if (isset($keys[$key])) {
35 1
                $context->notice(
36 1
                    'array.duplicate_keys',
37 1
                    sprintf(
38 1
                        'Duplicate array key "%s" in array definition (previously declared in line %d).',
39 1
                        $item->key instanceof Expr\Variable ? sprintf('$%s (resolved value: "%s")', $item->key->name, $key) : $key,
40 1
                        $keys[$key]->getLine()
41 1
                    ),
42
                    $item
43 1
                );
44
45 1
                $result = true;
46 1
            }
47
48 3
            $keys[$key] = $item;
49 37
        }
50
51 37
        return $result;
52
    }
53
54
    /**
55
     * @return array
56
     */
57 1
    public function getRegister()
58
    {
59
        return [
60
            Expr\Array_::class
61 1
        ];
62
    }
63
}
64