Skip to content

Commit d03a367

Browse files
authored
[12.x] Support enum values in Collection countBy method (#56830)
* Support enum usage in Collection countBy * Add tests for countBy using enum
1 parent 8a3af7b commit d03a367

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/Illuminate/Collections/LazyCollection.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ public function crossJoin(...$arrays)
319319
/**
320320
* Count the number of items in the collection by a field or using a callback.
321321
*
322-
* @param (callable(TValue, TKey): array-key)|string|null $countBy
322+
* @param (callable(TValue, TKey): array-key|\UnitEnum)|string|null $countBy
323323
* @return static<array-key, int>
324324
*/
325325
public function countBy($countBy = null)
@@ -332,7 +332,7 @@ public function countBy($countBy = null)
332332
$counts = [];
333333

334334
foreach ($this as $key => $value) {
335-
$group = $countBy($value, $key);
335+
$group = enum_value($countBy($value, $key));
336336

337337
if (empty($counts[$group])) {
338338
$counts[$group] = 0;

tests/Support/SupportCollectionTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -805,6 +805,9 @@ public function testCountByStandalone($collection)
805805

806806
$c = new $collection([1, 5, 1, 5, 5, 1]);
807807
$this->assertEquals([1 => 3, 5 => 3], $c->countBy()->all());
808+
809+
$c = new $collection([StaffEnum::James, StaffEnum::Joe, StaffEnum::Taylor]);
810+
$this->assertEquals(['James' => 1, 'Joe' => 1, 'Taylor' => 1], $c->countBy()->all());
808811
}
809812

810813
#[DataProvider('collectionClassProvider')]
@@ -815,6 +818,12 @@ public function testCountByWithKey($collection)
815818
['key' => 'b'], ['key' => 'b'], ['key' => 'b'],
816819
]);
817820
$this->assertEquals(['a' => 4, 'b' => 3], $c->countBy('key')->all());
821+
822+
$c = new $collection([
823+
['key' => TestBackedEnum::A],
824+
['key' => TestBackedEnum::B], ['key' => TestBackedEnum::B],
825+
]);
826+
$this->assertEquals([1 => 1, 2 => 2], $c->countBy('key')->all());
818827
}
819828

820829
#[DataProvider('collectionClassProvider')]
@@ -829,6 +838,9 @@ public function testCountableByWithCallback($collection)
829838
$this->assertEquals([true => 2, false => 3], $c->countBy(function ($i) {
830839
return $i % 2 === 0;
831840
})->all());
841+
842+
$c = new $collection(['A', 'A', 'B', 'A']);
843+
$this->assertEquals(['A' => 3, 'B' => 1], $c->countBy(static fn ($i) => TestStringBackedEnum::from($i))->all());
832844
}
833845

834846
public function testAdd()

0 commit comments

Comments
 (0)