From 75554ce741f13d4ede08c6d3d2776fb7baa4897b Mon Sep 17 00:00:00 2001 From: Caleb Porzio Date: Fri, 23 Jun 2017 14:24:44 -0400 Subject: [PATCH] [5.4] array_random helper (#19741) * Add 'array_random' helper with tests * replace array_rand usage with new array_random helper * Make random test more resilient --- .../Database/Connectors/ConnectionFactory.php | 2 +- src/Illuminate/Support/Arr.php | 11 +++++++++++ src/Illuminate/Support/helpers.php | 13 +++++++++++++ tests/Support/SupportArrTest.php | 8 ++++++++ 4 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Database/Connectors/ConnectionFactory.php b/src/Illuminate/Database/Connectors/ConnectionFactory.php index dabf8d69d4e0..98fb70188e27 100755 --- a/src/Illuminate/Database/Connectors/ConnectionFactory.php +++ b/src/Illuminate/Database/Connectors/ConnectionFactory.php @@ -138,7 +138,7 @@ protected function getWriteConfig(array $config) protected function getReadWriteConfig(array $config, $type) { return isset($config[$type][0]) - ? $config[$type][array_rand($config[$type])] + ? Arr::random($config[$type]) : $config[$type]; } diff --git a/src/Illuminate/Support/Arr.php b/src/Illuminate/Support/Arr.php index c6bf45678827..c2c1b210ee23 100755 --- a/src/Illuminate/Support/Arr.php +++ b/src/Illuminate/Support/Arr.php @@ -438,6 +438,17 @@ public static function pull(&$array, $key, $default = null) return $value; } + /** + * Get a random value from an array. + * + * @param array $array + * @return mixed + */ + public static function random($array) + { + return $array[array_rand($array)]; + } + /** * Set an array item to a given value using "dot" notation. * diff --git a/src/Illuminate/Support/helpers.php b/src/Illuminate/Support/helpers.php index 66d1d9d27e9a..4fc7f4eddb86 100755 --- a/src/Illuminate/Support/helpers.php +++ b/src/Illuminate/Support/helpers.php @@ -245,6 +245,19 @@ function array_pull(&$array, $key, $default = null) } } +if (! function_exists('array_random')) { + /** + * Get a random value from an array. + * + * @param array $array + * @return mixed + */ + function array_random($array) + { + return Arr::random($array); + } +} + if (! function_exists('array_set')) { /** * Set an array item to a given value using "dot" notation. diff --git a/tests/Support/SupportArrTest.php b/tests/Support/SupportArrTest.php index 7812310e776f..9ae9d7f4f145 100644 --- a/tests/Support/SupportArrTest.php +++ b/tests/Support/SupportArrTest.php @@ -399,6 +399,14 @@ public function testPull() $this->assertEquals(['emails' => ['joe@example.com' => 'Joe', 'jane@localhost' => 'Jane']], $array); } + public function testRandom() + { + $randomValue = Arr::random(['foo', 'bar', 'baz']); + + $this->assertInternalType('string', $randomValue); + $this->assertContains($randomValue, ['foo', 'bar', 'baz']); + } + public function testSet() { $array = ['products' => ['desk' => ['price' => 100]]];