Completed
Pull Request — master (#139)
by Kévin
03:44
created

ArrayDuplicateKeys::pass()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 19
c 2
b 0
f 0
nc 4
nop 2
dl 0
loc 33
ccs 22
cts 22
cp 1
crap 7
rs 6.7272
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