[9.x] Fix LazyCollection::makeIterator() to accept non Generator Function - #45881
Merged
taylorotwell merged 5 commits intoJan 31, 2023
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Introduction
LazyCollection accepts a generator function instead of a Generator in its constructor so that it can be called many times.
However, there is no logic implemented to check at runtime whether a received closure is really a generator function.
So, for example, if you pass the following Closure to LazyCollection::make()
Calling LazyCollection::getIterator() will result in the following error
This is because LazyCollection::makeIterator() called in LazyCollection::getIterator() returns the result of executing the function even if it is not a generator function.
What changed?
The original code looked like this
It is not known if $source is callable in the first place, and even if it is, it is not known if it returns Traversable or not.
Therefore, the following modifications have been made
I considered throwing an exception if $source was not a generator function, but seeing that LazyCollection::getArrayableItems() converts $item to an array of any value, I decided that makeIterator should do the same I decided that makeIterator should do the same.
Why wasn't this done in the constructor?
If you want to achieve the above in the constructor, use
However, I wanted to avoid the overhead of using Reflection as much as possible, and I also wanted to avoid wasting data in memory when a closure is executed in the constructor and an Iterator is returned.
thank you.