From 16472d1bce7b7619b3dceadbc2349053855397e6 Mon Sep 17 00:00:00 2001 From: Tonko Mulder Date: Wed, 19 Jun 2024 16:25:05 +0200 Subject: [PATCH] [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 --- src/Illuminate/Collections/Collection.php | 6 +++++- tests/Support/SupportCollectionTest.php | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index 6a225dce5c25..d7369d686591 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -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; } diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 8f72a9ca1e5e..e1e0a2d89cdb 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -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 */