From cd7672dd8eb6f8d6afa552a0494401918b68e1ba Mon Sep 17 00:00:00 2001 From: Joseph Silber Date: Thu, 13 Aug 2020 06:48:58 -0400 Subject: [PATCH] Support Collection#countBy($key) --- src/Illuminate/Support/LazyCollection.php | 6 +++--- tests/Support/SupportCollectionTest.php | 16 ++++++++++++++-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/Illuminate/Support/LazyCollection.php b/src/Illuminate/Support/LazyCollection.php index e17310aa81b8..8ddd5a8cabea 100644 --- a/src/Illuminate/Support/LazyCollection.php +++ b/src/Illuminate/Support/LazyCollection.php @@ -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 = []; diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index d4ff7de7f377..21a0e7154450 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -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()); @@ -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) {