Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CRM_Utils_Array::pathMove - Add helper to move an item within array tree #20866

Merged
merged 1 commit into from
Jul 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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