Skip to content

Commit

Permalink
[5.4] array_random helper (#19741)
Browse files Browse the repository at this point in the history
* Add 'array_random' helper with tests

* replace array_rand usage with new array_random helper

* Make random test more resilient
  • Loading branch information
calebporzio authored and taylorotwell committed Jun 23, 2017
1 parent 8d54d7f commit 75554ce
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Illuminate/Database/Connectors/ConnectionFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
}

Expand Down
11 changes: 11 additions & 0 deletions src/Illuminate/Support/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
13 changes: 13 additions & 0 deletions src/Illuminate/Support/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,14 @@ public function testPull()
$this->assertEquals(['emails' => ['[email protected]' => '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]]];
Expand Down

0 comments on commit 75554ce

Please sign in to comment.