From 516e7b07fdbf7f7d70cec5adda8f477d5e25ca5b Mon Sep 17 00:00:00 2001 From: Fernando Date: Thu, 1 May 2025 10:31:36 -0600 Subject: [PATCH 1/2] [12.x] Add support for callback evaluation in containsOneItem method --- src/Illuminate/Collections/Collection.php | 9 +++++++-- tests/Support/SupportCollectionTest.php | 4 ++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index 23e1af7bbfee..4636eb0174b6 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -712,12 +712,17 @@ public function isEmpty() } /** - * Determine if the collection contains a single item. + * Determine if the collection contains exactly one item. If a callback is provided, it checks if exactly one item matches the condition. * + * @param (callable(TValue, TKey): bool)|null $callback * @return bool */ - public function containsOneItem() + public function containsOneItem(?callable $callback = null): bool { + if ($callback) { + return $this->filter($callback)->count() === 1; + } + return $this->count() === 1; } diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 2edd11ca6718..7c8104b570ae 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -838,6 +838,10 @@ public function testContainsOneItem($collection) $this->assertFalse((new $collection([]))->containsOneItem()); $this->assertTrue((new $collection([1]))->containsOneItem()); $this->assertFalse((new $collection([1, 2]))->containsOneItem()); + + $this->assertFalse(collect([1, 2, 2])->containsOneItem(fn ($number) => $number === 2)); + $this->assertTrue(collect(['ant', 'bear', 'cat'])->containsOneItem(fn ($word) => strlen($word) === 4)); + $this->assertFalse(collect(['ant', 'bear', 'cat'])->containsOneItem(fn ($word) => strlen($word) > 4)); } public function testIterable() From 982204411ca57c267a5c236ea208c8b948611ae3 Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Fri, 2 May 2025 09:50:26 -0500 Subject: [PATCH 2/2] Update Collection.php --- src/Illuminate/Collections/Collection.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index 4636eb0174b6..95faa17a7121 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -712,7 +712,7 @@ public function isEmpty() } /** - * Determine if the collection contains exactly one item. If a callback is provided, it checks if exactly one item matches the condition. + * Determine if the collection contains exactly one item. If a callback is provided, determine if exactly one item matches the condition. * * @param (callable(TValue, TKey): bool)|null $callback * @return bool