mirror of
https://github.com/fzaninotto/Faker.git
synced 2025-03-21 15:59:52 +01:00
Lower randomElements defaults and add readme a note
Also tidied up the LengthException message, and made randomElements just a tiny bit faster by moving the array lookup to after a unique random value is chosen.
This commit is contained in:
parent
176507cc26
commit
a68fa66941
@ -177,6 +177,7 @@ Each of the generator properties (like `name`, `address`, and `lorem`) are calle
|
||||
randomNumber($from, $to) // 39049
|
||||
randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932
|
||||
randomLetter // 'b'
|
||||
randomElements($array = array ('a','b','c'), $count = 1) // array('c')
|
||||
randomElement($array = array ('a','b','c')) // 'b'
|
||||
numerify($string = '###') // '609'
|
||||
lexify($string = '????') // 'wgts'
|
||||
|
@ -132,13 +132,13 @@ class Base
|
||||
*
|
||||
* @return array New array with $count elements from $array
|
||||
*/
|
||||
public static function randomElements(array $array = array('a', 'b', 'c', 'd', 'e', 'f'), $count = 3)
|
||||
public static function randomElements(array $array = array('a', 'b', 'c'), $count = 1)
|
||||
{
|
||||
$allKeys = array_keys($array);
|
||||
$numKeys = count($allKeys);
|
||||
|
||||
if ($numKeys < $count) {
|
||||
throw new \LengthException("Cannot get $count elements, only " . count($array) . ' in array');
|
||||
throw new \LengthException(sprintf('Cannot get %d elements, only %d in array', $count, $numKeys));
|
||||
}
|
||||
|
||||
$highKey = $numKeys - 1;
|
||||
@ -146,13 +146,13 @@ class Base
|
||||
$numElements = 0;
|
||||
|
||||
while ($numElements < $count) {
|
||||
$key = $allKeys[mt_rand(0, $highKey)];
|
||||
if (isset($keys[$key])) {
|
||||
$num = mt_rand(0, $highKey);
|
||||
if (isset($keys[$num])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$keys[$key] = true;
|
||||
$elements[] = $array[$key];
|
||||
$keys[$num] = true;
|
||||
$elements[] = $array[$allKeys[$num]];
|
||||
$numElements++;
|
||||
}
|
||||
|
||||
|
@ -241,13 +241,13 @@ class BaseTest extends \PHPUnit_Framework_TestCase
|
||||
|
||||
public function testRandomElements()
|
||||
{
|
||||
$this->assertCount(3, BaseProvider::randomElements(), 'Should work without any input');
|
||||
$this->assertCount(1, 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'));
|
||||
$shuffled = BaseProvider::randomElements(array('foo', 'bar', 'baz'), 3);
|
||||
$this->assertContains('foo', $shuffled);
|
||||
$this->assertContains('bar', $shuffled);
|
||||
$this->assertContains('baz', $shuffled);
|
||||
|
Loading…
x
Reference in New Issue
Block a user