Skip to content

Commit 5c919df

Browse files
authored
[9.x] Check for \Stringable interface before casting using (string) (#41671)
* Check for `\Stringable` interface before casting using `(string)` Signed-off-by: Mior Muhammad Zaki <[email protected]> * wip
1 parent 8b23489 commit 5c919df

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/Illuminate/Collections/Collection.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -490,7 +490,7 @@ public function groupBy($groupBy, $preserveKeys = false)
490490
foreach ($groupKeys as $groupKey) {
491491
$groupKey = match (true) {
492492
is_bool($groupKey) => (int) $groupKey,
493-
is_object($groupKey) => (string) $groupKey,
493+
$groupKey instanceof \Stringable => (string) $groupKey,
494494
default => $groupKey,
495495
};
496496

tests/Support/SupportCollectionTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3023,6 +3023,30 @@ public function testGroupByAttribute($collection)
30233023
$this->assertEquals([1 => [['rating' => 1, 'url' => '1'], ['rating' => 1, 'url' => '1']], 2 => [['rating' => 2, 'url' => '2']]], $result->toArray());
30243024
}
30253025

3026+
/**
3027+
* @dataProvider collectionClassProvider
3028+
*/
3029+
public function testGroupByAttributeWithStringableKey($collection)
3030+
{
3031+
$data = new $collection($payload = [
3032+
['name' => Str::of('Laravel'), 'url' => '1'],
3033+
['name' => new HtmlString('Laravel'), 'url' => '1'],
3034+
['name' => new class()
3035+
{
3036+
public function __toString()
3037+
{
3038+
return 'Framework';
3039+
}
3040+
}, 'url' => '2', ],
3041+
]);
3042+
3043+
$result = $data->groupBy('name');
3044+
$this->assertEquals(['Laravel' => [$payload[0], $payload[1]], 'Framework' => [$payload[2]]], $result->toArray());
3045+
3046+
$result = $data->groupBy('url');
3047+
$this->assertEquals(['1' => [$payload[0], $payload[1]], '2' => [$payload[2]]], $result->toArray());
3048+
}
3049+
30263050
/**
30273051
* @dataProvider collectionClassProvider
30283052
*/

0 commit comments

Comments
 (0)