Skip to content

Commit

Permalink
Fix a unsuspected result from the split function in the Collection class
Browse files Browse the repository at this point in the history
See: #22090
  • Loading branch information
tvbeek committed May 3, 2018
1 parent 274dd48 commit 4a27f5a
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
36 changes: 36 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 4a27f5a

Please sign in to comment.