10000 [12.x] Add support for callback evaluation in containsOneItem method · laravel/framework@b109331 · GitHub
[go: up one dir, main page]

Skip to content

Commit b109331

Browse files
committed
[12.x] Add support for callback evaluation in containsOneItem method
1 parent b0cb237 commit b109331

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

src/Illuminate/Collections/Collection.php

+7-2
Original file line numberDiff line numberDiff line change
@@ -712,12 +712,17 @@ public function isEmpty()
712712
}
713713

714714
/**
715-
* Determine if the collection contains a single item.
715+
* Determine if the collection contains exactly one item. If a callback is provided, it checks if exactly one item matches the condition.
716716
*
717+
* @param (callable(TValue, TKey): bool)|null $callback
717718
* @return bool
718719
*/
719-
public function containsOneItem()
720+
public function containsOneItem(?callable $callback = null): bool
720721
{
722+
if ($callback) {
723+
return $this->filter($callback)->count() === 1;
724+
}
725+
721726
return $this->count() === 1;
722727
}
723728

tests/Support/SupportCollectionTest.php

+4
Original file line numberDiff line numberDiff line change
@@ -838,6 +838,10 @@ public function testContainsOneItem($collection)
838838
$this->assertFalse((new $collection([]))->containsOneItem());
839839
$this->assertTrue((new $collection([1]))->containsOneItem());
840840
$this->assertFalse((new $collection([1, 2]))->containsOneItem());
841+
842+
$this->assertFalse((collect([1, 2, 2])->containsOneItem(fn($number) => $number === 2)));
843+
$this->assertTrue((collect(['ant', 'bear', 'cat'])->containsOneItem(fn($word) => strlen($word) === 4)));
844+
$this->assertFalse((collect(['ant', 'bear', 'cat'])->containsOneItem(fn($word) => strlen($word) > 4)));
841845
}
842846

843847
public function testIterable()

0 commit comments

Comments
 (0)
0