Skip to content

Commit 413079d

Browse files
committed
ConstantArrayType - toPhpDocNode without keys if they are not necessary
1 parent 9592e9f commit 413079d

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

src/Type/Constant/ConstantArrayType.php

+17-2
Original file line numberDiff line numberDiff line change
@@ -1559,7 +1559,12 @@ public function makeOffsetRequired(Type $offsetType): self
15591559
public function toPhpDocNode(): TypeNode
15601560
{
15611561
$items = [];
1562+
$values = [];
1563+
$exportValuesOnly = true;
15621564
foreach ($this->keyTypes as $i => $keyType) {
1565+
if ($keyType->getValue() !== $i) {
1566+
$exportValuesOnly = false;
1567+
}
15631568
$keyPhpDocNode = $keyType->toPhpDocNode();
15641569
if (!$keyPhpDocNode instanceof ConstTypeNode) {
15651570
continue;
@@ -1574,14 +1579,24 @@ public function toPhpDocNode(): TypeNode
15741579
$keyNode = new IdentifierTypeNode($value);
15751580
}
15761581
}
1582+
1583+
$isOptional = $this->isOptionalKey($i);
1584+
if ($isOptional) {
1585+
$exportValuesOnly = false;
1586+
}
15771587
$items[] = new ArrayShapeItemNode(
15781588
$keyNode,
1579-
$this->isOptionalKey($i),
1589+
$isOptional,
1590+
$valueType->toPhpDocNode(),
1591+
);
1592+
$values[] = new ArrayShapeItemNode(
1593+
null,
1594+
$isOptional,
15801595
$valueType->toPhpDocNode(),
15811596
);
15821597
}
15831598

1584-
return new ArrayShapeNode($items);
1599+
return new ArrayShapeNode($exportValuesOnly ? $values : $items);
15851600
}
15861601

15871602
public static function isValidIdentifier(string $value): bool

tests/PHPStan/Type/TypeToPhpDocNodeTest.php

+33
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,39 @@ public function dataToPhpDocNode(): iterable
254254
]),
255255
'non-empty-list<mixed>',
256256
];
257+
258+
yield [
259+
new ConstantArrayType([
260+
new ConstantIntegerType(0),
261+
new ConstantIntegerType(1),
262+
], [
263+
new ConstantStringType('foo'),
264+
new ConstantStringType('bar'),
265+
]),
266+
"array{'foo', 'bar'}",
267+
];
268+
269+
yield [
270+
new ConstantArrayType([
271+
new ConstantIntegerType(0),
272+
new ConstantIntegerType(2),
273+
], [
274+
new ConstantStringType('foo'),
275+
new ConstantStringType('bar'),
276+
]),
277+
"array{0: 'foo', 2: 'bar'}",
278+
];
279+
280+
yield [
281+
new ConstantArrayType([
282+
new ConstantIntegerType(0),
283+
new ConstantIntegerType(1),
284+
], [
285+
new ConstantStringType('foo'),
286+
new ConstantStringType('bar'),
287+
], [2], [1]),
288+
"array{0: 'foo', 1?: 'bar'}",
289+
];
257290
}
258291

259292
/**

0 commit comments

Comments
 (0)