Skip to content

Commit

Permalink
CRM_Utils_Array::pathMove - Add helper to move an item within array tree
Browse files Browse the repository at this point in the history
  • Loading branch information
totten committed Jul 16, 2021
1 parent b6601e0 commit 884466e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
25 changes: 25 additions & 0 deletions CRM/Utils/Array.php
Original file line number Diff line number Diff line change
Expand Up @@ -1142,6 +1142,31 @@ public static function pathSet(&$values, $pathParts, $value) {
$r[$last] = $value;
}

/**
* Move an item in an array-tree (if it exists).
*
* @param array $values
* Data-tree
* @param string[] $src
* Old path for the existing item
* @param string[] $dest
* New path
* @param bool $cleanup
* @return int
* Number of items moved (0 or 1).
*/
public static function pathMove(&$values, $src, $dest, $cleanup = FALSE) {
if (!static::pathIsset($values, $src)) {
return 0;
}
else {
$value = static::pathGet($values, $src);
static::pathSet($values, $dest, $value);
static::pathUnset($values, $src, $cleanup);
return 1;
}
}

/**
* Convert a simple dictionary into separate key+value records.
*
Expand Down
19 changes: 18 additions & 1 deletion tests/phpunit/CRM/Utils/ArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public function testRemove() {
}

public function testGetSetPathParts() {
$arr = [
$arr = $arrOrig = [
'one' => '1',
'two' => [
'half' => 2,
Expand Down Expand Up @@ -188,6 +188,23 @@ public function testGetSetPathParts() {
$this->assertEquals(['second-third' => '2/3'], $arr['three']);
CRM_Utils_Array::pathUnset($arr, ['three', 'second-third'], TRUE);
$this->assertFalse(array_key_exists('three', $arr));

// pathMove(): Change location of an item
$arr = $arrOrig;
$this->assertEquals(2, $arr['two']['half']);
$this->assertTrue(!isset($arr['verb']['double']['half']));
$this->assertEquals(1, CRM_Utils_Array::pathMove($arr, ['two'], ['verb', 'double']));
$this->assertEquals(2, $arr['verb']['double']['half']);
$this->assertTrue(!isset($arr['two']['half']));

// pathMove(): If item doesn't exist, return 0.
$arr = $arrOrig;
$this->assertTrue(!isset($arr['not-a-src']));
$this->assertTrue(!isset($arr['not-a-dest']));
$this->assertEquals(0, CRM_Utils_Array::pathMove($arr, ['not-a-src'], ['not-a-dest']));
$this->assertTrue(!isset($arr['not-a-src']));
$this->assertTrue(!isset($arr['not-a-dest']));

}

public function getSortExamples() {
Expand Down

0 comments on commit 884466e

Please sign in to comment.