From 4a27f5aeacba5913d3fe8e0cb5637c8180081d45 Mon Sep 17 00:00:00 2001 From: Tobias van Beek Date: Thu, 3 May 2018 11:12:30 +0200 Subject: [PATCH] Fix a unsuspected result from the split function in the Collection class See: https://github.com/laravel/framework/issues/22090 --- src/Illuminate/Support/Collection.php | 20 ++++++++++++-- tests/Support/SupportCollectionTest.php | 36 +++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 7f6eefc4aa24..c2cd18b85692 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -1396,9 +1396,25 @@ public function split($numberOfGroups) return new static; } - $groupSize = ceil($this->count() / $numberOfGroups); + $groups = new static(); - return $this->chunk($groupSize); + $groupSize = floor($this->count() / $numberOfGroups); + + $remain = $this->count() % $numberOfGroups; + + $start = 0; + for ($i = 0; $i < $numberOfGroups; $i++) { + $size = $groupSize; + if ($i < $remain) { + $size++; + } + if ($size) { + $groups->push(new static(array_slice($this->items, $start, $size))); + $start += $size; + } + } + + return $groups; } /** diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 50b1516bdb6d..079fea8b9a5f 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -2407,6 +2407,42 @@ public function testSplitCollectionWithCountLessThenDivisor() ); } + public function testSplitCollectionIntoThreeWithCountOfFour() + { + $collection = new Collection(['a', 'b', 'c', 'd']); + + $this->assertEquals( + [['a', 'b'], ['c'], ['d']], + $collection->split(3)->map(function (Collection $chunk) { + return $chunk->values()->toArray(); + })->toArray() + ); + } + + public function testSplitCollectionIntoThreeWithCountOfFive() + { + $collection = new Collection(['a', 'b', 'c', 'd', 'e']); + + $this->assertEquals( + [['a', 'b'], ['c', 'd'], ['e']], + $collection->split(3)->map(function (Collection $chunk) { + return $chunk->values()->toArray(); + })->toArray() + ); + } + + public function testSplitCollectionIntoSixWithCountOfTen() + { + $collection = new Collection(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']); + + $this->assertEquals( + [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i'], ['j']], + $collection->split(6)->map(function (Collection $chunk) { + return $chunk->values()->toArray(); + })->toArray() + ); + } + public function testSplitEmptyCollection() { $collection = new Collection;