[5.4] fix for requesting 0 randoms on empty collection#20402
Merged
Conversation
previously if you requested 0 random items from an empty collection, it would mistakedly think we were requesting 1 item. this commit moves the check for a request of zero random items to the beginning, so we don't run into this issue. also add a test.
Contributor
Author
vlakoff
reviewed
Aug 3, 2017
| return new static; | ||
| } | ||
|
|
||
| if (($requested = $amount ?: 1) > ($count = $this->count())) { |
Contributor
There was a problem hiding this comment.
Now that 0 is a supported value, this ?: looks a bit dangerous. With PHP 7 we could just replace it with ??, but here with PHP 5 support, I'd suggest the following:
$requested = is_null($amount) ? 1 : $amount;
$count = $this->count();
if ($requested > $count) {
throw new InvalidArgumentException(
"You requested {$requested} items, but there are only {$count} items in the collection."
);
}
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.
previously if you requested 0 random items from an empty collection, it would mistakedly think we were requesting 1 item.
this commit moves the check for a request of zero random items to the beginning, so we don't run into this issue.
also add a test.