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

[10.x] Add support for BackedEnum in Collection groupBy method #47823

Merged
merged 2 commits into from Jul 24, 2023
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
1 change: 1 addition & 0 deletions src/Illuminate/Collections/Collection.php
Expand Up @@ -504,6 +504,7 @@ public function groupBy($groupBy, $preserveKeys = false)
foreach ($groupKeys as $groupKey) {
$groupKey = match (true) {
is_bool($groupKey) => (int) $groupKey,
$groupKey instanceof \BackedEnum => $groupKey->value,
$groupKey instanceof \Stringable => (string) $groupKey,
default => $groupKey,
};
Expand Down
1 change: 1 addition & 0 deletions tests/Support/Enums.php
Expand Up @@ -10,4 +10,5 @@ enum TestEnum
enum TestBackedEnum: int
{
case A = 1;
case B = 2;
}
14 changes: 14 additions & 0 deletions tests/Support/SupportCollectionTest.php
Expand Up @@ -3344,6 +3344,20 @@ public function sortByUrl(array $value)
return $value['url'];
}

/**
* @dataProvider collectionClassProvider
*/
public function testGroupByAttributeWithBackedEnumKey($collection)
{
$data = new $collection([
['rating' => TestBackedEnum::A, 'url' => '1'],
['rating' => TestBackedEnum::B, 'url' => '1'],
]);

$result = $data->groupBy('rating');
$this->assertEquals([TestBackedEnum::A->value => [['rating' => TestBackedEnum::A, 'url' => '1']], TestBackedEnum::B->value => [['rating' => TestBackedEnum::B, 'url' => '1']]], $result->toArray());
}

/**
* @dataProvider collectionClassProvider
*/
Expand Down