Skip to content

Commit 829394f

Browse files
DeanWunderDean Wunder
andauthored
[12.x] collapseWithKeys - Prevent exception in base case (#56002)
* collapseWithKeys - Ensure base case of already flat collection doesn't result in an exception. * 12.x Fix style error * 12.x Opting to return empty collection in this case instead to ensure functionality of Collection matches LazyCollection --------- Co-authored-by: Dean Wunder <dean@finao.com.au>
1 parent 4f4d556 commit 829394f

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

src/Illuminate/Collections/Collection.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,10 @@ public function collapseWithKeys()
165165
$results[$key] = $values;
166166
}
167167

168+
if (! $results) {
169+
return new static;
170+
}
171+
168172
return new static(array_replace(...$results));
169173
}
170174

tests/Support/SupportCollectionTest.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1772,6 +1772,10 @@ public function testCollapseWithKeys($collection)
17721772
{
17731773
$data = new $collection([[1 => 'a'], [3 => 'c'], [2 => 'b'], 'drop']);
17741774
$this->assertEquals([1 => 'a', 3 => 'c', 2 => 'b'], $data->collapseWithKeys()->all());
1775+
1776+
// Case with an already flat collection
1777+
$data = new $collection(['a', 'b', 'c']);
1778+
$this->assertEquals([], $data->collapseWithKeys()->all());
17751779
}
17761780

17771781
#[DataProvider('collectionClassProvider')]

0 commit comments

Comments
 (0)