Skip to content

Commit 75554ce

Browse files
calebporziotaylorotwell
authored andcommitted
[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
1 parent 8d54d7f commit 75554ce

File tree

4 files changed

+33
-1
lines changed

4 files changed

+33
-1
lines changed

src/Illuminate/Database/Connectors/ConnectionFactory.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ protected function getWriteConfig(array $config)
138138
protected function getReadWriteConfig(array $config, $type)
139139
{
140140
return isset($config[$type][0])
141-
? $config[$type][array_rand($config[$type])]
141+
? Arr::random($config[$type])
142142
: $config[$type];
143143
}
144144

src/Illuminate/Support/Arr.php

+11
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,17 @@ public static function pull(&$array, $key, $default = null)
438438
return $value;
439439
}
440440

441+
/**
442+
* Get a random value from an array.
443+
*
444+
* @param array $array
445+
* @return mixed
446+
*/
447+
public static function random($array)
448+
{
449+
return $array[array_rand($array)];
450+
}
451+
441452
/**
442453
* Set an array item to a given value using "dot" notation.
443454
*

src/Illuminate/Support/helpers.php

+13
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,19 @@ function array_pull(&$array, $key, $default = null)
245245
}
246246
}
247247

248+
if (! function_exists('array_random')) {
249+
/**
250+
* Get a random value from an array.
251+
*
252+
* @param array $array
253+
* @return mixed
254+
*/
255+
function array_random($array)
256+
{
257+
return Arr::random($array);
258+
}
259+
}
260+
248261
if (! function_exists('array_set')) {
249262
/**
250263
* Set an array item to a given value using "dot" notation.

tests/Support/SupportArrTest.php

+8
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,14 @@ public function testPull()
399399
$this->assertEquals(['emails' => ['[email protected]' => 'Joe', 'jane@localhost' => 'Jane']], $array);
400400
}
401401

402+
public function testRandom()
403+
{
404+
$randomValue = Arr::random(['foo', 'bar', 'baz']);
405+
406+
$this->assertInternalType('string', $randomValue);
407+
$this->assertContains($randomValue, ['foo', 'bar', 'baz']);
408+
}
409+
402410
public function testSet()
403411
{
404412
$array = ['products' => ['desk' => ['price' => 100]]];

0 commit comments

Comments
 (0)