From 393f41ddd1e36c4fe09c924d8916db6c2689e8ed Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Fri, 24 Jul 2015 20:38:06 -0700 Subject: [PATCH] CRM_Utils_Array - Add pathGet() and pathSet() --- CRM/Utils/Array.php | 43 +++++++++++++++++++++++++++ tests/phpunit/CRM/Utils/ArrayTest.php | 15 ++++++++++ 2 files changed, 58 insertions(+) diff --git a/CRM/Utils/Array.php b/CRM/Utils/Array.php index 9af358d6a8..d82ff2df4c 100644 --- a/CRM/Utils/Array.php +++ b/CRM/Utils/Array.php @@ -921,4 +921,47 @@ class CRM_Utils_Array { } } + /** + * Get a single value from an array-tre. + * + * @param array $arr + * Ex: array('foo'=>array('bar'=>123)). + * @param array $pathParts + * Ex: array('foo',bar'). + * @return mixed|NULL + * Ex 123. + */ + public static function pathGet($arr, $pathParts) { + $r = $arr; + foreach ($pathParts as $part) { + if (!isset($r[$part])) { + return NULL; + } + $r = $r[$part]; + } + return $r; + } + + /** + * Set a single value in an array tree. + * + * @param array $arr + * Ex: array('foo'=>array('bar'=>123)). + * @param array $pathParts + * Ex: array('foo',bar'). + * @param $value + * Ex: 456. + */ + public static function pathSet(&$arr, $pathParts, $value) { + $r = &$arr; + $last = array_pop($pathParts); + foreach ($pathParts as $part) { + if (!isset($r[$part])) { + $r[$part] = array(); + } + $r = &$r[$part]; + } + $r[$last] = $value; + } + } diff --git a/tests/phpunit/CRM/Utils/ArrayTest.php b/tests/phpunit/CRM/Utils/ArrayTest.php index 6b2ee68110..7d21674de7 100644 --- a/tests/phpunit/CRM/Utils/ArrayTest.php +++ b/tests/phpunit/CRM/Utils/ArrayTest.php @@ -127,4 +127,19 @@ class CRM_Utils_ArrayTest extends CiviUnitTestCase { $this->assertEquals($data, array('six' => 6)); } + public function testGetSetPathParts() { + $arr = array( + 'one' => '1', + 'two' => array( + 'half' => 2, + ), + ); + $this->assertEquals('1', CRM_Utils_Array::pathGet($arr, array('one'))); + $this->assertEquals('2', CRM_Utils_Array::pathGet($arr, array('two', 'half'))); + $this->assertEquals(NULL, CRM_Utils_Array::pathGet($arr, array('zoo', 'half'))); + CRM_Utils_Array::pathSet($arr, array('zoo', 'half'), '3'); + $this->assertEquals(3, CRM_Utils_Array::pathGet($arr, array('zoo', 'half'))); + $this->assertEquals(3, $arr['zoo']['half']); + } + } -- 2.25.1