Skip to content

Commit

Permalink
Merge pull request #12192 from eileenmcnaughton/utils
Browse files Browse the repository at this point in the history
Further additional utility function for handling odd array structure
  • Loading branch information
JoeMurray authored May 25, 2018
2 parents 78ce089 + f18ccb7 commit 02666f9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
16 changes: 16 additions & 0 deletions CRM/Utils/Array.php
Original file line number Diff line number Diff line change
Expand Up @@ -1197,4 +1197,20 @@ public static function recursiveValue($array, $path, $default = NULL) {
return $array;
}

/**
* Append the value to the array using the key provided.
*
* e.g if value is 'llama' & path is [0, 'email', 'location'] result will be
* [0 => ['email' => ['location' => 'llama']]
*
* @param $path
* @param $value
*
* @return array
*/
public static function recursiveBuild($path, $value) {
$arrayKey = array_shift($path);
return [$arrayKey => (empty($path) ? $value : self::recursiveBuild($path, $value))];
}

}
24 changes: 24 additions & 0 deletions tests/phpunit/CRM/Utils/ArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -298,4 +298,28 @@ public function testRecursiveValue($array, $path, $default, $expected) {
$this->assertEquals($expected, $result);
}

/**
* Get values for build test.
*/
public function getBuildValueExamples() {
return [
[
[0, 'email', 2, 'location'], [0 => ['email' => [2 => ['location' => 'llama']]]]
]
];
}

/**
* Test the build recursive function.
*
* @param $path
* @param $expected
*
* @dataProvider getBuildValueExamples
*/
public function testBuildRecursiveValue($path, $expected) {
$result = CRM_Utils_Array::recursiveBuild($path, 'llama');
$this->assertEquals($expected, $result);
}

}

0 comments on commit 02666f9

Please sign in to comment.