Skip to content

Commit 16472d1

Browse files
authored
[10.x] fix handle shift() on an empty collection (#51841)
* 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
1 parent d3f16e8 commit 16472d1

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/Illuminate/Collections/Collection.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1134,7 +1134,11 @@ public function shift($count = 1)
11341134
throw new InvalidArgumentException('Number of shifted items may not be less than zero.');
11351135
}
11361136

1137-
if ($count === 0 || $this->isEmpty()) {
1137+
if ($this->isEmpty()) {
1138+
return null;
1139+
}
1140+
1141+
if ($count === 0) {
11381142
return new static;
11391143
}
11401144

tests/Support/SupportCollectionTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,23 @@ public function testShiftReturnsAndRemovesFirstXItemsInCollection()
404404
(new Collection(['foo', 'bar', 'baz']))->shift(-2);
405405
}
406406

407+
public function testShiftReturnsNullOnEmptyCollection()
408+
{
409+
$itemFoo = new \stdClass();
410+
$itemFoo->text = 'f';
411+
$itemBar = new \stdClass();
412+
$itemBar->text = 'x';
413+
414+
$items = collect([$itemFoo, $itemBar]);
415+
416+
$foo = $items->shift();
417+
$bar = $items->shift();
418+
419+
$this->assertSame('f', $foo?->text);
420+
$this->assertSame('x', $bar?->text);
421+
$this->assertNull($items->shift());
422+
}
423+
407424
/**
408425
* @dataProvider collectionClassProvider
409426
*/

0 commit comments

Comments
 (0)