|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace ArrayKeyLastExisting; |
| 4 | + |
| 5 | +use function PHPStan\Testing\assertType; |
| 6 | + |
| 7 | +/** |
| 8 | + * Mirrors the RichParser pattern: the array starts empty, gets entries |
| 9 | + * appended in some loop branches, and an existing entry's nested key is |
| 10 | + * updated in others. `if ($key !== null)` should be enough to let PHPStan |
| 11 | + * track that `$arr[$key]` exists and the deep write should preserve the |
| 12 | + * outer shape, just like `isset($arr[$key])` does. |
| 13 | + */ |
| 14 | +function appendThenUpdateLast(string $name, string $comment): void |
| 15 | +{ |
| 16 | + $identifiers = []; |
| 17 | + $c = rand(100, 200); |
| 18 | + for ($i = 0; $i < $c; $i++) { |
| 19 | + if (rand(0, 1) === 1) { |
| 20 | + $key = array_key_last($identifiers); |
| 21 | + if ($key !== null) { |
| 22 | + $identifiers[$key]['comment'] = $comment; |
| 23 | + } |
| 24 | + continue; |
| 25 | + } |
| 26 | + |
| 27 | + $identifiers[] = ['name' => $name, 'comment' => null]; |
| 28 | + } |
| 29 | + |
| 30 | + assertType('list<array{name: string, comment: string|null}>', $identifiers); |
| 31 | +} |
| 32 | + |
| 33 | +function appendThenUpdateFirst(string $name, string $comment): void |
| 34 | +{ |
| 35 | + $identifiers = []; |
| 36 | + $c = rand(100, 200); |
| 37 | + for ($i = 0; $i < $c; $i++) { |
| 38 | + if (rand(0, 1) === 1) { |
| 39 | + $key = array_key_first($identifiers); |
| 40 | + if ($key !== null) { |
| 41 | + $identifiers[$key]['comment'] = $comment; |
| 42 | + } |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + $identifiers[] = ['name' => $name, 'comment' => null]; |
| 47 | + } |
| 48 | + |
| 49 | + assertType('list<array{name: string, comment: string|null}>', $identifiers); |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * @param list<array{name: 'x', comment: null}> $list |
| 54 | + */ |
| 55 | +function maybeEmptyArray(array $list): void |
| 56 | +{ |
| 57 | + $key = array_key_last($list); |
| 58 | + if ($key !== null) { |
| 59 | + assertType('array{name: \'x\', comment: null}', $list[$key]); |
| 60 | + $list[$key]['comment'] = 'hello'; |
| 61 | + assertType('non-empty-list<array{name: \'x\', comment: \'hello\'}>', $list); |
| 62 | + } |
| 63 | +} |
0 commit comments