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

Skip to content

Commit e728b73

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

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

src/Illuminate/Collections/Collection.php

+8-3
Original file line numberDiff line numberDiff line change
@@ -711,13 +711,18 @@ public function isEmpty()
711711
return empty($this->items);
712712
}
713713

714-
/**
715-
* Determine if the collection contains a single item.
714+
/**
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