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