diff --git a/src/Faker/Provider/Base.php b/src/Faker/Provider/Base.php index ed348999..add1e4e9 100644 --- a/src/Faker/Provider/Base.php +++ b/src/Faker/Provider/Base.php @@ -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 * diff --git a/test/Faker/Provider/BaseTest.php b/test/Faker/Provider/BaseTest.php index 64967b69..497c02e4 100644 --- a/test/Faker/Provider/BaseTest.php +++ b/test/Faker/Provider/BaseTest.php @@ -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); + } }