Skip to content

Commit 5682bdb

Browse files
authored
Support Collection#countBy($key) (#33852)
1 parent 9c539ca commit 5682bdb

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

src/Illuminate/Support/LazyCollection.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -248,9 +248,9 @@ public function crossJoin(...$arrays)
248248
*/
249249
public function countBy($countBy = null)
250250
{
251-
if (is_null($countBy)) {
252-
$countBy = $this->identity();
253-
}
251+
$countBy = is_null($countBy)
252+
? $this->identity()
253+
: $this->valueRetriever($countBy);
254254

255255
return new static(function () use ($countBy) {
256256
$counts = [];

tests/Support/SupportCollectionTest.php

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -478,7 +478,7 @@ public function testCountable($collection)
478478
/**
479479
* @dataProvider collectionClassProvider
480480
*/
481-
public function testCountableByWithoutPredicate($collection)
481+
public function testCountByStandalone($collection)
482482
{
483483
$c = new $collection(['foo', 'foo', 'foo', 'bar', 'bar', 'foobar']);
484484
$this->assertEquals(['foo' => 3, 'bar' => 2, 'foobar' => 1], $c->countBy()->all());
@@ -493,7 +493,19 @@ public function testCountableByWithoutPredicate($collection)
493493
/**
494494
* @dataProvider collectionClassProvider
495495
*/
496-
public function testCountableByWithPredicate($collection)
496+
public function testCountByWithKey($collection)
497+
{
498+
$c = new $collection([
499+
['key' => 'a'], ['key' => 'a'], ['key' => 'a'], ['key' => 'a'],
500+
['key' => 'b'], ['key' => 'b'], ['key' => 'b'],
501+
]);
502+
$this->assertEquals(['a' => 4, 'b' => 3], $c->countBy('key')->all());
503+
}
504+
505+
/**
506+
* @dataProvider collectionClassProvider
507+
*/
508+
public function testCountableByWithCallback($collection)
497509
{
498510
$c = new $collection(['alice', 'aaron', 'bob', 'carla']);
499511
$this->assertEquals(['a' => 2, 'b' => 1, 'c' => 1], $c->countBy(function ($name) {

0 commit comments

Comments
 (0)