From f18ccb71c313b7d6562d30594c3a51ed496990f9 Mon Sep 17 00:00:00 2001 From: eileen Date: Thu, 24 May 2018 15:31:21 +1200 Subject: [PATCH] Further utility on handling odd array structure --- CRM/Utils/Array.php | 16 ++++++++++++++++ tests/phpunit/CRM/Utils/ArrayTest.php | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/CRM/Utils/Array.php b/CRM/Utils/Array.php index 4829078fc0..f4938febf8 100644 --- a/CRM/Utils/Array.php +++ b/CRM/Utils/Array.php @@ -1197,4 +1197,20 @@ class CRM_Utils_Array { 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))]; + } + } diff --git a/tests/phpunit/CRM/Utils/ArrayTest.php b/tests/phpunit/CRM/Utils/ArrayTest.php index 1c32c0c681..34d9d6c30a 100644 --- a/tests/phpunit/CRM/Utils/ArrayTest.php +++ b/tests/phpunit/CRM/Utils/ArrayTest.php @@ -298,4 +298,28 @@ class CRM_Utils_ArrayTest extends CiviUnitTestCase { $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); + } + } -- 2.25.1