Skip to content

Commit

Permalink
Support Collection#countBy($key) (#33852)
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber committed Aug 13, 2020
1 parent 9c539ca commit 5682bdb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
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

0 comments on commit 5682bdb

Please sign in to comment.