Skip to content

Commit

Permalink
Merge pull request #20787 from totten/master-path-unset
Browse files Browse the repository at this point in the history
CRM_Utils_Array - Implement pathUnset() method
  • Loading branch information
eileenmcnaughton authored Jul 7, 2021
2 parents 6d2cfff + 61bdc08 commit 73bd44d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
34 changes: 34 additions & 0 deletions CRM/Utils/Array.php
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,40 @@ public static function pathIsset($values, $path) {
return TRUE;
}

/**
* Remove a key from an array.
*
* This is a helper for when the calling function does not know how many layers deep
* the path array is so cannot easily check.
*
* @param array $values
* @param array $path
* @param bool $cleanup
* If removed item leaves behind an empty array, should you remove the empty array?
* @return bool
* TRUE if anything has been removed. FALSE if no changes were required.
*/
public static function pathUnset(&$values, $path, $cleanup = FALSE) {
if (count($path) === 1) {
if (isset($values[$path[0]])) {
unset($values[$path[0]]);
return TRUE;
}
else {
return FALSE;
}
}
else {
$next = array_shift($path);
$r = static::pathUnset($values[$next], $path, $cleanup);
if ($cleanup && $values[$next] === []) {
$r = TRUE;
unset($values[$next]);
}
return $r;
}
}

/**
* Set a single value in an array tree.
*
Expand Down
17 changes: 17 additions & 0 deletions tests/phpunit/CRM/Utils/ArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,13 +133,30 @@ public function testGetSetPathParts() {
'two' => [
'half' => 2,
],
'three' => [
'first-third' => '1/3',
'second-third' => '2/3',
],
];
$this->assertEquals('1', CRM_Utils_Array::pathGet($arr, ['one']));
$this->assertEquals('2', CRM_Utils_Array::pathGet($arr, ['two', 'half']));
$this->assertEquals(NULL, CRM_Utils_Array::pathGet($arr, ['zoo', 'half']));
CRM_Utils_Array::pathSet($arr, ['zoo', 'half'], '3');
$this->assertEquals(3, CRM_Utils_Array::pathGet($arr, ['zoo', 'half']));
$this->assertEquals(3, $arr['zoo']['half']);

$arrCopy = $arr;
$this->assertEquals(FALSE, CRM_Utils_Array::pathUnset($arr, ['does-not-exist']));
$this->assertEquals($arrCopy, $arr);

$this->assertEquals(TRUE, CRM_Utils_Array::pathUnset($arr, ['two', 'half'], FALSE));
$this->assertEquals([], $arr['two']);
$this->assertTrue(array_key_exists('two', $arr));

CRM_Utils_Array::pathUnset($arr, ['three', 'first-third'], TRUE);
$this->assertEquals(['second-third' => '2/3'], $arr['three']);
CRM_Utils_Array::pathUnset($arr, ['three', 'second-third'], TRUE);
$this->assertFalse(array_key_exists('three', $arr));
}

public function getSortExamples() {
Expand Down

0 comments on commit 73bd44d

Please sign in to comment.