From e0ac0a1c1368e7191bc1212bb71cc9e2b6d673a5 Mon Sep 17 00:00:00 2001 From: duncanxia Date: Fri, 20 Jan 2023 00:03:59 +0800 Subject: [PATCH] ArrayList support returning references (#289) --- src/Utils/ArrayList.php | 8 +++++--- tests/Utils/ArrayList.phpt | 10 ++++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/Utils/ArrayList.php b/src/Utils/ArrayList.php index 54684c751..4f32061b4 100644 --- a/src/Utils/ArrayList.php +++ b/src/Utils/ArrayList.php @@ -41,11 +41,13 @@ public static function from(array $array): static /** * Returns an iterator over all items. - * @return \ArrayIterator + * @return \Iterator */ - public function getIterator(): \ArrayIterator + public function &getIterator(): \Iterator { - return new \ArrayIterator($this->list); + foreach ($this->list as &$item) { + yield $item; + } } diff --git a/tests/Utils/ArrayList.phpt b/tests/Utils/ArrayList.phpt index 2a60da4d5..462f7a757 100644 --- a/tests/Utils/ArrayList.phpt +++ b/tests/Utils/ArrayList.phpt @@ -157,3 +157,13 @@ test('', function () { unset($list['key']); }, OutOfRangeException::class, 'Offset invalid or out of range'); }); + + +test('returning references', function () { + $list = ArrayList::from([1, 2, 3]); + foreach ($list as $key => &$value) { + $value = 'new'; + } + + Assert::same(['new', 'new', 'new'], iterator_to_array($list)); +});