Skip to content

Commit

Permalink
Assume the user knows what they are doing when setting values
Browse files Browse the repository at this point in the history
  • Loading branch information
borkweb committed Dec 19, 2024
1 parent 80d1dbe commit 68d2312
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 12 deletions.
19 changes: 7 additions & 12 deletions src/Arrays/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -1081,6 +1081,11 @@ static function( $key ) {
* @return array Full array with the key set to the specified value.
*/
public static function set( $array, $key, $value ): array {
// Convert input to array if not already
if ( ! is_array( $array ) ) {
$array = [];
}

// If key is a string with dots, convert to array
if ( is_string( $key ) ) {
$key = explode( '.', $key );
Expand All @@ -1098,18 +1103,8 @@ public static function set( $array, $key, $value ): array {

// Traverse through each key segment
foreach ( $segments as $segment ) {
// If we're trying to set an array key on a non-array value, throw an error
if ( isset( $current[ $segment ] ) && ! is_array( $current[ $segment ] ) ) {
throw new \RuntimeException(
sprintf(
'Cannot set key "%s" - parent segment is not an array',
implode( '.', $key )
)
);
}

// Create empty array if segment doesn't exist
if ( ! isset( $current[ $segment ] ) ) {
// If the current segment is a Closure or not an array, convert it to an array
if ( ! isset( $current[ $segment ] ) || ! is_array( $current[ $segment ] ) ) {
$current[ $segment ] = [];
}

Expand Down
16 changes: 16 additions & 0 deletions tests/wpunit/SetTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,20 @@ public function test_set() {
$this->assertTrue(Arr::has($array, 'foo.bar'));
$this->assertFalse(Arr::has($array, 'foo.baz'));
}

public function test_set_with_closure() {
$array = [];
$array = Arr::set($array, 'foo', function () {
return 'bar';
});

// This set should override the closure.
$array = Arr::set($array, 'foo.bar', function () {
return 'baz';
});

$this->assertTrue(Arr::has($array, 'foo'));
$this->assertIsArray(Arr::get($array, 'foo'));
$this->assertTrue(Arr::has($array, 'foo.bar'));
}
}

0 comments on commit 68d2312

Please sign in to comment.