-
Notifications
You must be signed in to change notification settings - Fork 28
[5.4] Collection::random(int $amount) should always return a collection #304
Comments
I like your proposal, but it would break backward compatibility. public function randomSubset($count)
{
if(empty($this->items)) {
return new static;
}
if($count == 1) {
$key = array_rand($this->items);
return new static([$this->items[$key]]);
}
return $this->random($count);
} |
Or preferably |
In only would break things if you explicitely call I don't think it would be an issue to add this in 5.4 (just edited the title for clarity) |
This is a valid point, but nevertheless behaviour of this method changes drastically from returning a value to returning a one element collection, which in my opinion breaks BC. You should ping Taylor on Slack to get feedback. |
I know it breaks BC, but breaking changes are allowed between Laravel minor versions (it doesn't follow semver) |
Yes, that's why I think you should talk to Taylor about this, so you don't waste time writing tests. |
@sebastiandedeyne Great proposal, makes complete sense and is very consistent with other great APIs (thinking of Ruby's That BC break should indeed be fine, especially as it affects an edge case that should either be considered a bug (when passing a variable) or is very easy to find (when passing 1 directly). As for getting Taylor's feedback, that's exactly what this place is for... |
You may be right. Ping @taylorotwell |
I feel like this makes fairly good sense. |
Currently, if you call
$collection->random(1)
, you'll get a single item back. This makes sense if there isn't a parameter set, but if1
is explicitly passed through, it should return a new collection instance. This keeps it consistent with passing in any other integer.Example use case: if you want to retrieve a random number of random items (useful in seeders), you can't predict the return value:
Proposed solution: change the default value to
null
, so$collection->random()
still returns a single item.If there's interest I'm willing to spin up a PR!
The text was updated successfully, but these errors were encountered: