8000 [12.x] Add support for callback evaluation in containsOneItem method by fernandokbs · Pull Request #55622 · laravel/framework · GitHub
[go: up one dir, main page]

Skip to content

[12.x] Add support for callback evaluation in containsOneItem method #55622

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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, determine 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;
}

Expand Down
4 changes: 4 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
0