Completed
Pull Request — master (#139)
by Kévin
22:48 queued 19:51
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\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