Completed
Pull Request — master (#86)
by Kévin
03:16
created

ArrayDuplicateKeys   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 8

Test Coverage

Coverage 82.76%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 65
ccs 24
cts 29
cp 0.8276
rs 10
c 1
b 0
f 0
wmc 9
lcom 0
cbo 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
C pass() 0 34 7
A getRegister() 0 6 1
A getConfiguration() 0 9 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 PhpParser\Node\Scalar;
10
use PHPSA\Analyzer\Pass;
11
use PHPSA\Context;
12
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
13
14
class ArrayDuplicateKeys implements Pass\AnalyzerPassInterface, Pass\ConfigurablePassInterface
15
{
16
    /**
17
     * @param Expr\Array_ $expr
18
     * @param Context $context
19
     * @return bool
20
     */
21 23
    public function pass(Expr\Array_ $expr, Context $context)
22
    {
23 23
        $result = false;
24 23
        $keys = [];
25
26
        /** @var Expr\ArrayItem $item */
27 23
        foreach ($expr->items as $item) {
28 9
            $compiledKey = $context->getExpressionCompiler()->compile($item->key);
29
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
    /**
67
     * @return TreeBuilder
68
     */
69
    public function getConfiguration()
70
    {
71
        $treeBuilder = new TreeBuilder();
72
        $treeBuilder->root('array.duplicate_keys')
73
            ->canBeDisabled()
74
        ;
75
76
        return $treeBuilder;
77
    }
78
}
79