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

ArrayDuplicateKeys   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 7

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 59
ccs 24
cts 24
cp 1
rs 10
c 2
b 0
f 0
wmc 8
lcom 0
cbo 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
C pass() 0 33 7
A getRegister() 0 6 1
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