mirror of
https://github.com/fzaninotto/Faker.git
synced 2025-03-25 09:49:56 +01:00
add Faker\Provider\Base::randomElements
This commit is contained in:
parent
1800e885b5
commit
cae91904b8
@ -123,6 +123,29 @@ class Base
|
||||
return chr(mt_rand(97, 122));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns random 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.
|
||||
* @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', 'd', 'e', 'f'), $count = 3)
|
||||
{
|
||||
if (count($array) < $count) {
|
||||
throw new \LengthException("Cannot get $count elements, only " . count($array) . ' in array');
|
||||
}
|
||||
$elements = array();
|
||||
while (count($elements) < $count) {
|
||||
$key = static::randomKey($array);
|
||||
$elements[$key] = $array[$key];
|
||||
}
|
||||
|
||||
return array_values($elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random element from a passed array
|
||||
*
|
||||
|
@ -229,4 +229,27 @@ class BaseTest extends \PHPUnit_Framework_TestCase
|
||||
sort($values);
|
||||
$this->assertEquals(array(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9), $values);
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedException LengthException
|
||||
* @expectedExceptionMessage Cannot get 2 elements, only 1 in array
|
||||
*/
|
||||
public function testRandomElementsThrowsWhenRequestingTooManyKeys()
|
||||
{
|
||||
BaseProvider::randomElements(array('foo'), 2);
|
||||
}
|
||||
|
||||
public function testRandomElements()
|
||||
{
|
||||
$this->assertCount(3, BaseProvider::randomElements(), 'Should work without any input');
|
||||
|
||||
$empty = BaseProvider::randomElements(array(), 0);
|
||||
$this->assertInternalType('array', $empty);
|
||||
$this->assertCount(0, $empty);
|
||||
|
||||
$shuffled = BaseProvider::randomElements(array('foo', 'bar', 'baz'));
|
||||
$this->assertContains('foo', $shuffled);
|
||||
$this->assertContains('bar', $shuffled);
|
||||
$this->assertContains('baz', $shuffled);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user