diff --git a/src/Arrays/Arr.php b/src/Arrays/Arr.php index c792850..e7a56b4 100644 --- a/src/Arrays/Arr.php +++ b/src/Arrays/Arr.php @@ -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 ); @@ -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 ] = []; } diff --git a/tests/wpunit/SetTest.php b/tests/wpunit/SetTest.php index fd5953b..cb16c5c 100644 --- a/tests/wpunit/SetTest.php +++ b/tests/wpunit/SetTest.php @@ -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')); + } }