|
| 1 | +<?php // lint >= 7.4 |
| 2 | + |
| 3 | +namespace Bug5372; |
| 4 | + |
| 5 | +use function PHPStan\Testing\assertType; |
| 6 | + |
| 7 | +/** |
| 8 | + * @template TKey of array-key |
| 9 | + * @template T |
| 10 | + */ |
| 11 | +class Collection |
| 12 | +{ |
| 13 | + |
| 14 | + /** @var array<TKey, T> */ |
| 15 | + private $values; |
| 16 | + |
| 17 | + /** |
| 18 | + * @param array<TKey, T> $values |
| 19 | + */ |
| 20 | + public function __construct(array $values) |
| 21 | + { |
| 22 | + $this->values = $values; |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * @template V |
| 27 | + * |
| 28 | + * @param callable(T): V $callback |
| 29 | + * |
| 30 | + * @return self<TKey, V> |
| 31 | + */ |
| 32 | + public function map(callable $callback): self { |
| 33 | + return new self(array_map($callback, $this->values)); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * @template V of string |
| 38 | + * |
| 39 | + * @param callable(T): V $callback |
| 40 | + * |
| 41 | + * @return self<TKey, V> |
| 42 | + */ |
| 43 | + public function map2(callable $callback): self { |
| 44 | + return new self(array_map($callback, $this->values)); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +class Foo |
| 49 | +{ |
| 50 | + |
| 51 | + /** @param Collection<int, string> $list */ |
| 52 | + function takesStrings(Collection $list): void { |
| 53 | + echo serialize($list); |
| 54 | + } |
| 55 | + |
| 56 | + /** @param class-string $classString */ |
| 57 | + public function doFoo(string $classString) |
| 58 | + { |
| 59 | + $col = new Collection(['foo', 'bar']); |
| 60 | + assertType('Bug5372\Collection<int, string>', $col); |
| 61 | + |
| 62 | + $newCol = $col->map(static fn(string $var): string => $var . 'bar'); |
| 63 | + assertType('Bug5372\Collection<int, string>', $newCol); |
| 64 | + $this->takesStrings($newCol); |
| 65 | + |
| 66 | + $newCol = $col->map(static fn(string $var): string => $classString); |
| 67 | + assertType('Bug5372\Collection<int, string>', $newCol); |
| 68 | + $this->takesStrings($newCol); |
| 69 | + |
| 70 | + $newCol = $col->map2(static fn(string $var): string => $classString); |
| 71 | + assertType('Bug5372\Collection<int, class-string>', $newCol); |
| 72 | + $this->takesStrings($newCol); |
| 73 | + } |
| 74 | + |
| 75 | +} |
0 commit comments