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

ArrayDuplicateKeys   A

Complexity

Total Complexity 8

Size/Duplication

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