From 38206945762f456352c0f39a6456d850948a2ff1 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 31 Mar 2021 19:44:13 +0200 Subject: [PATCH] Add unshift method to collection --- src/Illuminate/Collections/Collection.php | 12 ++++++++++++ tests/Support/SupportCollectionTest.php | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index 68fb3cecc100..194e1e7b52e4 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -807,6 +807,18 @@ public function prepend($value, $key = null) return $this; } + /** + * Push an item onto the beginning of the collection. + * + * @param mixed $value + * @param mixed $key + * @return $this + */ + public function unshift($value, $key = null) + { + return $this->prepend(...func_get_args()); + } + /** * Push one or more items onto the end of the collection. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 3c09a0018def..8dd73360dd8a 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -3261,6 +3261,27 @@ public function testPrepend() ); } + public function testUnshift() + { + $c = new Collection(['one', 'two', 'three', 'four']); + $this->assertEquals( + ['zero', 'one', 'two', 'three', 'four'], + $c->unshift('zero')->all() + ); + + $c = new Collection(['one' => 1, 'two' => 2]); + $this->assertEquals( + ['zero' => 0, 'one' => 1, 'two' => 2], + $c->unshift(0, 'zero')->all() + ); + + $c = new Collection(['one' => 1, 'two' => 2]); + $this->assertEquals( + [null => 0, 'one' => 1, 'two' => 2], + $c->unshift(0, null)->all() + ); + } + public function testPushWithOneItem() { $expected = [