[12.x] Add Collection::containsManyItems() method#58312
[12.x] Add Collection::containsManyItems() method#58312taylorotwell merged 4 commits intolaravel:12.xfrom
Collection::containsManyItems() method#58312Conversation
| if ($callback) { | ||
| return $this->filter($callback)->count() > 1; | ||
| } | ||
|
|
||
| return $this->count() > 1; |
There was a problem hiding this comment.
If the goal here is to just see if there are at least two items in the collection matching the filter, wouldn't it be better to call each() and then break the loop once you've met the limit of 2?
There was a problem hiding this comment.
This is basically identical to the existing containsOneItem method to maintain consistency between the two:
framework/src/Illuminate/Collections/Collection.php
Lines 729 to 736 in cc03bd4
| * Determine if the collection contains multiple items. If a callback is provided, determine if multiple items match the condition. | ||
| * | ||
| * @param (callable(TValue, TKey): bool)|null $callback | ||
| * @return bool |
There was a problem hiding this comment.
I wonder if it would make sense to add an assertion here and in the two corresponding methods
| * @return bool | |
| * @return bool | |
| * @phpstan-assert-if-true non-empty-array<TKey, TValue> $this->items |
There was a problem hiding this comment.
I followed suit with the containsOneItem method doc block:
framework/src/Illuminate/Collections/Collection.php
Lines 723 to 736 in cc03bd4
There was a problem hiding this comment.
Nobody said, there wasn't room for improvement. With this argument, we'd be stuck in the stone age forever.
There was a problem hiding this comment.
lol easy -- its a doc block
There was a problem hiding this comment.
It's more than a comment. It improves static analysis.
This PR adds the
containsManyItemsmethod to collections, like thecontainsOneItemmethod that already exists.This assists in keeping a uniform syntax in situations where you need to take a code path depending on the collection being empty, having one item, or having many: