Skip to content

Commit

Permalink
ArrayHash: fixed iteration with reference (BC break) [Closes #253]
Browse files Browse the repository at this point in the history
BC break, because it doesn't return RecursiveArrayIterator
  • Loading branch information
dg committed Feb 2, 2023
1 parent 0bb0999 commit cacdbf5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
8 changes: 5 additions & 3 deletions src/Utils/ArrayHash.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,13 @@ public static function from(array $array, bool $recursive = true): static

/**
* Returns an iterator over all items.
* @return \RecursiveArrayIterator<array-key, T>
* @return \Iterator<int|string, T>
*/
public function getIterator(): \RecursiveArrayIterator
public function &getIterator(): \Iterator
{
return new \RecursiveArrayIterator((array) $this);
foreach ((array) $this as $key => $foo) {
yield $key => $this->$key;
}
}


Expand Down
12 changes: 11 additions & 1 deletion tests/Utils/ArrayHash.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ test('', function () {
'j' => 'Jack',
'children' => $list['children'],
'c' => 'Jim',
], iterator_to_array(new RecursiveIteratorIterator($list, RecursiveIteratorIterator::SELF_FIRST)));
], iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($list), RecursiveIteratorIterator::SELF_FIRST)));
});


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

Assert::count(0, $hash);
});


test('iteration with reference', function () {
$hash = ArrayHash::from([1, 2, 3]);
foreach ($hash as $key => &$value) {
$value = 'new';
}

Assert::same(['new', 'new', 'new'], (array) $hash);
});

0 comments on commit cacdbf5

Please sign in to comment.