Skip to content
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

[7.x] Support Collection#countBy($key) #33852

Merged
merged 1 commit into from Aug 13, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/Illuminate/Support/LazyCollection.php
Expand Up @@ -248,9 +248,9 @@ public function crossJoin(...$arrays)
*/
public function countBy($countBy = null)
{
if (is_null($countBy)) {
$countBy = $this->identity();
}
$countBy = is_null($countBy)
? $this->identity()
: $this->valueRetriever($countBy);

return new static(function () use ($countBy) {
$counts = [];
Expand Down
16 changes: 14 additions & 2 deletions tests/Support/SupportCollectionTest.php
Expand Up @@ -478,7 +478,7 @@ public function testCountable($collection)
/**
* @dataProvider collectionClassProvider
*/
public function testCountableByWithoutPredicate($collection)
public function testCountByStandalone($collection)
{
$c = new $collection(['foo', 'foo', 'foo', 'bar', 'bar', 'foobar']);
$this->assertEquals(['foo' => 3, 'bar' => 2, 'foobar' => 1], $c->countBy()->all());
Expand All @@ -493,7 +493,19 @@ public function testCountableByWithoutPredicate($collection)
/**
* @dataProvider collectionClassProvider
*/
public function testCountableByWithPredicate($collection)
public function testCountByWithKey($collection)
{
$c = new $collection([
['key' => 'a'], ['key' => 'a'], ['key' => 'a'], ['key' => 'a'],
['key' => 'b'], ['key' => 'b'], ['key' => 'b'],
]);
$this->assertEquals(['a' => 4, 'b' => 3], $c->countBy('key')->all());
}

/**
* @dataProvider collectionClassProvider
*/
public function testCountableByWithCallback($collection)
{
$c = new $collection(['alice', 'aaron', 'bob', 'carla']);
$this->assertEquals(['a' => 2, 'b' => 1, 'c' => 1], $c->countBy(function ($name) {
Expand Down