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

[5.4] Always return a collection when calling Collection::random with a parameter #16865

Merged
merged 1 commit into from
Dec 20, 2016
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
8 changes: 6 additions & 2 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -892,7 +892,7 @@ public function put($key, $value)
/**
* Get one or more items randomly from the collection.
*
* @param int $amount
* @param int|null $amount
* @return mixed
*
* @throws \InvalidArgumentException
Expand All @@ -905,10 +905,14 @@ public function random($amount = 1)

$keys = array_rand($this->items, $amount);

if ($amount == 1) {
if (count(func_get_args()) == 0) {
return $this->items[$keys];
}

if (! is_array($keys)) {
$keys = [$keys];
}

return new static(array_intersect_key($this->items, array_flip($keys)));
}

Expand Down
15 changes: 12 additions & 3 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -814,15 +814,24 @@ public function testRandom()
{
$data = new Collection([1, 2, 3, 4, 5, 6]);

$random = $data->random();
$this->assertInternalType('integer', $random);
$this->assertContains($random, $data->all());
$random = $data->random(1);
$this->assertInstanceOf(Collection::class, $random);
$this->assertCount(1, $random);

$random = $data->random(3);
$this->assertInstanceOf(Collection::class, $random);
$this->assertCount(3, $random);
}

public function testRandomWithoutArgument()
{
$data = new Collection([1, 2, 3, 4, 5, 6]);

$random = $data->random();
$this->assertInternalType('integer', $random);
$this->assertContains($random, $data->all());
}

/**
* @expectedException InvalidArgumentException
*/
Expand Down