Skip to content

Commit

Permalink
Always return a collection when calling Collection::random with a par…
Browse files Browse the repository at this point in the history
…ameter (#16865)
  • Loading branch information
sebastiandedeyne authored and taylorotwell committed Dec 20, 2016
1 parent 7aaa53c commit 9a6ca3a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
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

0 comments on commit 9a6ca3a

Please sign in to comment.