Skip to content

Commit

Permalink
Treat ConstantArrayType as covariant in its keys and values
Browse files Browse the repository at this point in the history
This should be safe because it is copy-on-write
  • Loading branch information
jiripudil committed Jun 17, 2023
1 parent 72c4f4c commit d417dc3
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Type/Constant/ConstantArrayType.php
Original file line number Diff line number Diff line change
Expand Up @@ -1368,7 +1368,7 @@ public function inferTemplateTypes(Type $receivedType): TemplateTypeMap

public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
{
$variance = $positionVariance->compose(TemplateTypeVariance::createInvariant());
$variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
$references = [];

foreach ($this->keyTypes as $type) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -219,4 +219,9 @@ public function testBug8880(): void
]);
}

public function testBug9161(): void
{
$this->analyse([__DIR__ . '/data/bug-9161.php'], []);
}

}
39 changes: 39 additions & 0 deletions tests/PHPStan/Rules/Generics/data/bug-9161.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php declare(strict_types = 1); // lint >= 8.0

namespace Bug9161;

/**
* @template-covariant TKey of int|string
* @template-covariant TValue
*/
final class Map
{
/**
* @param array<TKey, TValue> $items
*/
public function __construct(
private array $items = [],
) {
}

/**
* @return array<TKey, TValue>
*/
public function toArray(): array
{
return $this->items;
}

/**
* @return list<array{0: TKey, 1: TValue}>
*/
public function toPairs(): array
{
$pairs = [];
foreach ($this->items as $key => $value) {
$pairs[] = [$key, $value];
}

return $pairs;
}
}

0 comments on commit d417dc3

Please sign in to comment.