Skip to content

Commit 4947deb

Browse files
committed
ArrayHash: fixed iteration with reference (BC break) [Closes #253]
BC break, because it doesn't return RecursiveArrayIterator
1 parent 50c432c commit 4947deb

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

src/Utils/ArrayHash.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,13 @@ public static function from(array $array, bool $recursive = true): static
3737

3838
/**
3939
* Returns an iterator over all items.
40-
* @return \RecursiveArrayIterator<array-key, T>
40+
* @return \Iterator<int|string, T>
4141
*/
42-
public function getIterator(): \RecursiveArrayIterator
42+
public function &getIterator(): \Iterator
4343
{
44-
return new \RecursiveArrayIterator((array) $this);
44+
foreach ((array) $this as $key => $foo) {
45+
yield $key => $this->$key;
46+
}
4547
}
4648

4749

tests/Utils/ArrayHash.phpt

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ test('', function () {
117117
'j' => 'Jack',
118118
'children' => $list['children'],
119119
'c' => 'Jim',
120-
], iterator_to_array(new RecursiveIteratorIterator($list, RecursiveIteratorIterator::SELF_FIRST)));
120+
], iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($list), RecursiveIteratorIterator::SELF_FIRST)));
121121
});
122122

123123

@@ -204,3 +204,13 @@ test('PHP 7 changed behavior https://3v4l.org/2A1pf', function () {
204204

205205
Assert::count(0, $hash);
206206
});
207+
208+
209+
test('iteration with reference', function () {
210+
$hash = ArrayHash::from([1, 2, 3]);
211+
foreach ($hash as $key => &$value) {
212+
$value = 'new';
213+
}
214+
215+
Assert::same(['new', 'new', 'new'], (array) $hash);
216+
});

0 commit comments

Comments
 (0)