Skip to content

Commit f1cc53a

Browse files
jiripudilondrejmirtes
authored andcommitted
Treat ConstantArrayType as covariant in its keys and values
This should be safe because it is copy-on-write
1 parent 77bfdc5 commit f1cc53a

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

src/Type/Constant/ConstantArrayType.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1368,7 +1368,7 @@ public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
13681368

13691369
public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
13701370
{
1371-
$variance = $positionVariance->compose(TemplateTypeVariance::createInvariant());
1371+
$variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
13721372
$references = [];
13731373

13741374
foreach ($this->keyTypes as $type) {

tests/PHPStan/Rules/Generics/MethodSignatureVarianceRuleTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,4 +219,9 @@ public function testBug8880(): void
219219
]);
220220
}
221221

222+
public function testBug9161(): void
223+
{
224+
$this->analyse([__DIR__ . '/data/bug-9161.php'], []);
225+
}
226+
222227
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php declare(strict_types = 1); // lint >= 8.0
2+
3+
namespace Bug9161;
4+
5+
/**
6+
* @template-covariant TKey of int|string
7+
* @template-covariant TValue
8+
*/
9+
final class Map
10+
{
11+
/**
12+
* @param array<TKey, TValue> $items
13+
*/
14+
public function __construct(
15+
private array $items = [],
16+
) {
17+
}
18+
19+
/**
20+
* @return array<TKey, TValue>
21+
*/
22+
public function toArray(): array
23+
{
24+
return $this->items;
25+
}
26+
27+
/**
28+
* @return list<array{0: TKey, 1: TValue}>
29+
*/
30+
public function toPairs(): array
31+
{
32+
$pairs = [];
33+
foreach ($this->items as $key => $value) {
34+
$pairs[] = [$key, $value];
35+
}
36+
37+
return $pairs;
38+
}
39+
}

0 commit comments

Comments
 (0)