Completed
Pull Request — master (#139)
by Kévin
03:44
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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 9
ccs 0
cts 5
cp 0
crap 2
rs 9.6666
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 PHPSA\Analyzer\Helper\DefaultMetadataPassTrait;
10
use PHPSA\Analyzer\Pass;
11
use PHPSA\Context;
12
13
class ArrayDuplicateKeys implements Pass\AnalyzerPassInterface
14
{
15
    use DefaultMetadataPassTrait;
16
17
    const DESCRIPTION = <<<DESC
18
This inspection reports any duplicated keys on array creation expression.
19
If multiple elements in the array declaration use the same key, only the last
20
one will be used as all others are overwritten.
21
DESC;
22
23
    /**
24
     * @param Expr\Array_ $expr
25
     * @param Context $context
26
     * @return bool
27
     */
28 26
    public function pass(Expr\Array_ $expr, Context $context)
29
    {
30 26
        $result = false;
31 26
        $keys = [];
32
33
        /** @var Expr\ArrayItem $item */
34 26
        foreach ($expr->items as $item) {
35 10
            $compiledKey = $context->getExpressionCompiler()->compile($item->key);
36 10
            if (!$compiledKey->isTypeKnown() || !$compiledKey->isScalar() || !$compiledKey->hasValue()) {
37 8
                continue;
38
            }
39
40 3
            $key = $compiledKey->getValue();
41
42 3
            if (isset($keys[$key])) {
43 1
                $context->notice(
44 1
                    'array.duplicate_keys',
45 1
                    sprintf(
46 1
                        'Duplicate array key "%s" in array definition (previously declared in line %d).',
47 1
                        $item->key instanceof Expr\Variable ? sprintf('$%s (resolved value: "%s")', $item->key->name, $key) : $key,
48 1
                        $keys[$key]->getLine()
49 1
                    ),
50
                    $item
51 1
                );
52
53 1
                $result = true;
54 1
            }
55
56 3
            $keys[$key] = $item;
57 26
        }
58
59 26
        return $result;
60
    }
61
62
    /**
63
     * @return array
64
     */
65 1
    public function getRegister()
66
    {
67
        return [
68
            Expr\Array_::class
69 1
        ];
70
    }
71
}
72