From c17dff4c7af5aa0a6cbc805b0d291b3867e587f2 Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Sun, 10 Jun 2018 15:41:42 -0400 Subject: [PATCH] Improve CRM_Utils_Array::recursiveBuild to work with existing arrays. --- CRM/Utils/Array.php | 16 ++++++++++++++-- tests/phpunit/CRM/Utils/ArrayTest.php | 14 ++++++++++---- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/CRM/Utils/Array.php b/CRM/Utils/Array.php index f4938febf8..a9d6cdd07e 100644 --- a/CRM/Utils/Array.php +++ b/CRM/Utils/Array.php @@ -1205,12 +1205,24 @@ class CRM_Utils_Array { * * @param $path * @param $value + * @param array $source * * @return array */ - public static function recursiveBuild($path, $value) { + public static function recursiveBuild($path, $value, $source = []) { $arrayKey = array_shift($path); - return [$arrayKey => (empty($path) ? $value : self::recursiveBuild($path, $value))]; + // Recurse through array keys + if ($path) { + if (!isset($source[$arrayKey])) { + $source[$arrayKey] = []; + } + $source[$arrayKey] = self::recursiveBuild($path, $value, $source[$arrayKey]); + } + // Final iteration + else { + $source[$arrayKey] = $value; + } + return $source; } } diff --git a/tests/phpunit/CRM/Utils/ArrayTest.php b/tests/phpunit/CRM/Utils/ArrayTest.php index 34d9d6c30a..979e5bbefa 100644 --- a/tests/phpunit/CRM/Utils/ArrayTest.php +++ b/tests/phpunit/CRM/Utils/ArrayTest.php @@ -304,8 +304,14 @@ class CRM_Utils_ArrayTest extends CiviUnitTestCase { public function getBuildValueExamples() { return [ [ - [0, 'email', 2, 'location'], [0 => ['email' => [2 => ['location' => 'llama']]]] - ] + [], [0, 'email', 2, 'location'], [0 => ['email' => [2 => ['location' => 'llama']]]], + ], + [ + ['foo', 'bar', [['donkey']]], [2, 0, 1], ['foo', 'bar', [['donkey', 'llama']]], + ], + [ + ['a' => [1, 2, 3], 'b' => ['x' => [], 'y' => ['a' => 'donkey', 'b' => 'bear'], 'z' => [4, 5, 6]]], ['b', 'y', 'b'], ['a' => [1, 2, 3], 'b' => ['x' => [], 'y' => ['a' => 'donkey', 'b' => 'llama'], 'z' => [4, 5, 6]]], + ], ]; } @@ -317,8 +323,8 @@ class CRM_Utils_ArrayTest extends CiviUnitTestCase { * * @dataProvider getBuildValueExamples */ - public function testBuildRecursiveValue($path, $expected) { - $result = CRM_Utils_Array::recursiveBuild($path, 'llama'); + public function testBuildRecursiveValue($source, $path, $expected) { + $result = CRM_Utils_Array::recursiveBuild($path, 'llama', $source); $this->assertEquals($expected, $result); } -- 2.25.1