Skip to content
This repository has been archived by the owner on Dec 11, 2020. It is now read-only.

Add allowDuplicates option to randomElements() #1060

Merged
merged 2 commits into from
Oct 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
18 changes: 11 additions & 7 deletions src/Faker/Provider/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,18 +161,19 @@ public static function randomAscii()
/**
* Returns randomly ordered subsequence of $count elements from a provided array
*
* @param array $array Array to take elements from. Defaults to a-f
* @param integer $count Number of elements to take.
* @param array $array Array to take elements from. Defaults to a-f
* @param integer $count Number of elements to take.
* @param boolean $allowDuplicates Allow elements to be picked several times. Defaults to false
* @throws \LengthException When requesting more elements than provided
*
* @return array New array with $count elements from $array
*/
public static function randomElements(array $array = array('a', 'b', 'c'), $count = 1)
public static function randomElements(array $array = array('a', 'b', 'c'), $count = 1, $allowDuplicates = false)
{
$allKeys = array_keys($array);
$numKeys = count($allKeys);

if ($numKeys < $count) {
if (!$allowDuplicates && $numKeys < $count) {
throw new \LengthException(sprintf('Cannot get %d elements, only %d in array', $count, $numKeys));
}

Expand All @@ -182,11 +183,14 @@ public static function randomElements(array $array = array('a', 'b', 'c'), $coun

while ($numElements < $count) {
$num = mt_rand(0, $highKey);
if (isset($keys[$num])) {
continue;

if (!$allowDuplicates) {
if (isset($keys[$num])) {
continue;
}
$keys[$num] = true;
}

$keys[$num] = true;
$elements[] = $array[$allKeys[$num]];
$numElements++;
}
Expand Down
4 changes: 4 additions & 0 deletions test/Faker/Provider/BaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -547,5 +547,9 @@ public function testRandomElements()
$this->assertContains('foo', $shuffled);
$this->assertContains('bar', $shuffled);
$this->assertContains('baz', $shuffled);

$allowDuplicates = BaseProvider::randomElements(array('foo', 'bar'), 3, true);
$this->assertCount(3, $allowDuplicates);
$this->assertContainsOnly('string', $allowDuplicates);
}
}