Skip to content

Commit

Permalink
ArrayList support iteration with reference (#289)
Browse files Browse the repository at this point in the history
  • Loading branch information
duncanxia97 authored and dg committed Feb 1, 2023
1 parent de2c733 commit dbfaaac
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/Utils/ArrayList.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,13 @@ public static function from(array $array): static

/**
* Returns an iterator over all items.
* @return \ArrayIterator<int, T>
* @return \Iterator<int, T>
*/
public function getIterator(): \ArrayIterator
public function &getIterator(): \Iterator
{
return new \ArrayIterator($this->list);
foreach ($this->list as &$item) {
yield $item;
}
}


Expand Down
10 changes: 10 additions & 0 deletions tests/Utils/ArrayList.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,13 @@ test('', function () {
unset($list['key']);
}, OutOfRangeException::class, 'Offset invalid or out of range');
});


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

Assert::same(['new', 'new', 'new'], iterator_to_array($list));
});

0 comments on commit dbfaaac

Please sign in to comment.