Skip to content

Commit

Permalink
[10.x] fix handle shift() on an empty collection (#51841)
Browse files Browse the repository at this point in the history
* add test for collection shift on a empty collection

* fix collection shift when dealing with an empty collection

* place the `isEmpty()` check before the count check

* update naming and assert the actual values
  • Loading branch information
Treggats authored Jun 19, 2024
1 parent d3f16e8 commit 16472d1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1134,7 +1134,11 @@ public function shift($count = 1)
throw new InvalidArgumentException('Number of shifted items may not be less than zero.');
}

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

if ($count === 0) {
return new static;
}

Expand Down
17 changes: 17 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,23 @@ public function testShiftReturnsAndRemovesFirstXItemsInCollection()
(new Collection(['foo', 'bar', 'baz']))->shift(-2);
}

public function testShiftReturnsNullOnEmptyCollection()
{
$itemFoo = new \stdClass();
$itemFoo->text = 'f';
$itemBar = new \stdClass();
$itemBar->text = 'x';

$items = collect([$itemFoo, $itemBar]);

$foo = $items->shift();
$bar = $items->shift();

$this->assertSame('f', $foo?->text);
$this->assertSame('x', $bar?->text);
$this->assertNull($items->shift());
}

/**
* @dataProvider collectionClassProvider
*/
Expand Down

0 comments on commit 16472d1

Please sign in to comment.