From cae91904b8e4060196d3a4d85267e648e7e00a6b Mon Sep 17 00:00:00 2001
From: David Stensland <me@terite.com>
Date: Wed, 5 Mar 2014 12:16:15 -0500
Subject: [PATCH] add Faker\Provider\Base::randomElements

---
 src/Faker/Provider/Base.php      | 23 +++++++++++++++++++++++
 test/Faker/Provider/BaseTest.php | 23 +++++++++++++++++++++++
 2 files changed, 46 insertions(+)

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);
+    }
 }