Skip to content

Commit 3e9304a

Browse files
phpstan-botclaude
andcommitted
Add test showing reviewer's by-ref with-key sub-element case already works
The reviewer pointed out that modifying array sub-elements through a by-reference foreach with a key variable also had issues. Testing confirms this case already works correctly on the current branch — both with and without a key variable. The reviewer's example was likely tested against the stable phpstan.org release which runs an older version. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent e1c87da commit 3e9304a

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?php
2+
3+
namespace Bug1940WithKey;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/**
8+
* Reviewer's exact example: by-ref with key, modifying sub-element.
9+
* This already worked before this PR.
10+
* @param list<array{one: string}> $a
11+
*/
12+
function byRefWithKeyModifySubElement(array $a): void
13+
{
14+
foreach ($a as $k => &$testArray) {
15+
$testArray['two'] = 'two';
16+
}
17+
18+
assertType("list<array{one: string, two: 'two'}>", $a);
19+
}
20+
21+
/**
22+
* By-ref WITHOUT key, modifying sub-element.
23+
* Parallel case to the reviewer's example but without key variable.
24+
* @param list<array{one: string}> $a
25+
*/
26+
function byRefWithoutKeyModifySubElement(array $a): void
27+
{
28+
foreach ($a as &$testArray) {
29+
$testArray['two'] = 'two';
30+
}
31+
32+
assertType("list<array{one: string, two: 'two'}>", $a);
33+
}
34+
35+
/**
36+
* By-ref with key, direct overwrite (already worked before this PR)
37+
* @param array<int, string> $arr
38+
*/
39+
function byRefWithKeyDirectOverwrite(array $arr): void
40+
{
41+
foreach ($arr as $k => &$v) {
42+
$v = 1;
43+
}
44+
45+
assertType('array<int, 1>', $arr);
46+
}
47+
48+
/**
49+
* By-ref without key, direct overwrite (this PR's main fix)
50+
* @param array<int, string> $arr
51+
*/
52+
function byRefWithoutKeyDirectOverwrite(array $arr): void
53+
{
54+
foreach ($arr as &$v) {
55+
$v = 1;
56+
}
57+
58+
assertType('array<int, 1>', $arr);
59+
}

0 commit comments

Comments
 (0)