Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unshift method to Collection #51344

Merged
merged 1 commit into from
May 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -995,6 +995,19 @@ public function push(...$values)
return $this;
}

/**
* Prepend one or more items to the beginning of the collection.
*
* @param TValue ...$values
* @return $this
*/
public function unshift(...$values)
{
array_unshift($this->items, ...$values);

return $this;
}

/**
* Push all of the given items onto the collection.
*
Expand Down
45 changes: 45 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3788,6 +3788,51 @@ public function testPushWithMultipleItems()
$this->assertSame($expected, $actual);
}

public function testUnshiftWithOneItem()
{
$expected = [
0 => 'Jonny from Laroe',
1 => ['who' => 'Jonny', 'preposition' => 'from', 'where' => 'Laroe'],
2 => ['a', 'b', 'c'],
3 => 4,
4 => 5,
5 => 6,
];

$data = new Collection([4, 5, 6]);
$data->unshift(['a', 'b', 'c']);
$data->unshift(['who' => 'Jonny', 'preposition' => 'from', 'where' => 'Laroe']);
$actual = $data->unshift('Jonny from Laroe')->toArray();

$this->assertSame($expected, $actual);
}

public function testUnshiftWithMultipleItems()
{
$expected = [
0 => 'a',
1 => 'b',
2 => 'c',
3 => 'Jonny',
4 => 'from',
5 => 'Laroe',
6 => 'Jonny',
7 => 'from',
8 => 'Laroe',
9 => 4,
10 => 5,
11 => 6,
];

$data = new Collection([4, 5, 6]);
$data->unshift('Jonny', 'from', 'Laroe');
$data->unshift(...[11 => 'Jonny', 12 => 'from', 13 => 'Laroe']);
$data->unshift(...collect(['a', 'b', 'c']));
$actual = $data->unshift(...[])->toArray();

$this->assertSame($expected, $actual);
}

#[DataProvider('collectionClassProvider')]
public function testZip($collection)
{
Expand Down