Skip to content

Commit

Permalink
fix out of bounds shift and pop behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Aug 9, 2021
1 parent f629792 commit bd89575
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -797,9 +797,15 @@ public function pop($count = 1)
return array_pop($this->items);
}

if ($this->isEmpty()) {
return new static;
}

$results = [];

foreach (range(1, $count) as $item) {
$collectionCount = $this->count();

foreach (range(1, min($count, $collectionCount)) as $item) {
array_push($results, array_pop($this->items));
}

Expand Down Expand Up @@ -963,7 +969,13 @@ public function shift($count = 1)

$results = [];

foreach (range(1, $count) as $item) {
if ($this->isEmpty()) {
return new static;
}

$collectionCount = $this->count();

foreach (range(1, min($count, $collectionCount)) as $item) {
array_push($results, array_shift($this->items));
}

Expand Down
4 changes: 4 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,8 @@ public function testPopReturnsAndRemovesLastXItemsInCollection()

$this->assertEquals(new Collection(['baz', 'bar']), $c->pop(2));
$this->assertSame('foo', $c->first());

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

public function testShiftReturnsAndRemovesFirstItemInCollection()
Expand All @@ -249,6 +251,8 @@ public function testShiftReturnsAndRemovesFirstXItemsInCollection()

$this->assertEquals(new Collection(['foo', 'bar']), $data->shift(2));
$this->assertSame('baz', $data->first());

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

/**
Expand Down

0 comments on commit bd89575

Please sign in to comment.