Skip to content

Commit

Permalink
[10.x] Fix collection shift less than one item (#51686)
Browse files Browse the repository at this point in the history
* fix collection shift less than 1

* throw exception earlier

* Update Collection.php

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
faissaloux and taylorotwell authored Jun 3, 2024
1 parent 0bf2a4c commit 8154eb6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

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

/**
Expand Down

0 comments on commit 8154eb6

Please sign in to comment.