Skip to content

Commit 4f2408e

Browse files
committed
Added support for ConstantString unions in DuplicateKeysInLiteralArraysRule
1 parent e56064f commit 4f2408e

File tree

3 files changed

+42
-16
lines changed

3 files changed

+42
-16
lines changed

Diff for: src/Rules/Arrays/DuplicateKeysInLiteralArraysRule.php

+15-16
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
use PHPStan\Rules\Rule;
1010
use PHPStan\Rules\RuleErrorBuilder;
1111
use PHPStan\Type\Constant\ConstantIntegerType;
12-
use PHPStan\Type\ConstantScalarType;
1312
use function array_keys;
1413
use function count;
1514
use function implode;
@@ -79,29 +78,29 @@ public function processNode(Node $node, Scope $scope): array
7978
}
8079
}
8180

82-
if (!$keyType instanceof ConstantScalarType) {
81+
if (count($keyType->getConstantScalarValues()) === 0) {
8382
$autoGeneratedIndex = false;
8483
continue;
8584
}
8685

87-
$value = $keyType->getValue();
88-
$printedValue = $key !== null
89-
? $this->exprPrinter->printExpr($key)
90-
: $value;
86+
foreach ($keyType->getConstantScalarValues() as $value) {
87+
$printedValue = $key !== null
88+
? $this->exprPrinter->printExpr($key)
89+
: $value;
90+
$printedValues[$value][] = $printedValue;
9191

92-
$printedValues[$value][] = $printedValue;
92+
if (!isset($valueLines[$value])) {
93+
$valueLines[$value] = $item->getStartLine();
94+
}
9395

94-
if (!isset($valueLines[$value])) {
95-
$valueLines[$value] = $item->getStartLine();
96-
}
96+
$previousCount = count($values);
97+
$values[$value] = $printedValue;
98+
if ($previousCount !== count($values)) {
99+
continue;
100+
}
97101

98-
$previousCount = count($values);
99-
$values[$value] = $printedValue;
100-
if ($previousCount !== count($values)) {
101-
continue;
102+
$duplicateKeys[$value] = true;
102103
}
103-
104-
$duplicateKeys[$value] = true;
105104
}
106105

107106
$messages = [];

Diff for: tests/PHPStan/Rules/Arrays/DuplicateKeysInLiteralArraysRuleTest.php

+12
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,18 @@ public function testDuplicateKeys(): void
6161
'Array has 2 duplicate keys with value -41 (-41, -41).',
6262
76,
6363
],
64+
[
65+
'Array has 2 duplicate keys with value \'foo\' (\'foo\', $key).',
66+
102,
67+
],
68+
[
69+
'Array has 2 duplicate keys with value \'bar\' (\'bar\', $key).',
70+
103,
71+
],
72+
[
73+
'Array has 2 duplicate keys with value \'key\' (\'key\', $key2).',
74+
105,
75+
],
6476
]);
6577
}
6678

Diff for: tests/PHPStan/Rules/Arrays/data/duplicate-keys.php

+15
Original file line numberDiff line numberDiff line change
@@ -92,4 +92,19 @@ public function doWithoutKeys(int $int)
9292
];
9393
}
9494

95+
/**
96+
* @param 'foo'|'bar' $key
97+
*/
98+
public function doUnionKeys(string $key): void
99+
{
100+
$key2 = 'key';
101+
$a = [
102+
'foo' => 'foo',
103+
'bar' => 'bar',
104+
$key => 'foo|bar',
105+
'key' => 'bar',
106+
$key2 => 'foo',
107+
];
108+
}
109+
95110
}

0 commit comments

Comments
 (0)