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

[5.7] Fix a unsuspected result from the split function in the Collection class #24088

Merged
merged 1 commit into from
May 3, 2018
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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