Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

[10.x] Fix collection shift less than one item #51686

Merged
merged 3 commits into from
Jun 3, 2024
Merged
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
13 changes: 10 additions & 3 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@
use Illuminate\Contracts\Support\CanBeEscapedWhenCastToString;
use Illuminate\Support\Traits\EnumeratesValues;
use Illuminate\Support\Traits\Macroable;
use InvalidArgumentException;
use stdClass;
use Traversable;

@@ -1124,17 +1125,23 @@ public function search($value, $strict = false)
*
* @param int $count
* @return static<int, TValue>|TValue|null
*
* @throws \InvalidArgumentException
*/
public function shift($count = 1)
{
if ($count === 1) {
return array_shift($this->items);
if ($count < 0) {
throw new InvalidArgumentException('Number of shifted items may not be less than zero.');
}

if ($this->isEmpty()) {
if ($count === 0 || $this->isEmpty()) {
return new static;
}

if ($count === 1) {
return array_shift($this->items);
}

$results = [];

$collectionCount = $this->count();
11 changes: 11 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
@@ -391,6 +391,17 @@ public function testShiftReturnsAndRemovesFirstXItemsInCollection()
$this->assertSame('baz', $data->first());

$this->assertEquals(new Collection(['foo', 'bar', 'baz']), (new Collection(['foo', 'bar', 'baz']))->shift(6));

$data = new Collection(['foo', 'bar', 'baz']);

$this->assertEquals(new Collection([]), $data->shift(0));
$this->assertEquals(collect(['foo', 'bar', 'baz']), $data);

$this->expectException('InvalidArgumentException');
(new Collection(['foo', 'bar', 'baz']))->shift(-1);

$this->expectException('InvalidArgumentException');
(new Collection(['foo', 'bar', 'baz']))->shift(-2);
}

/**