| 1 |
<?php |
| 2 |
/** |
| 3 |
* General utilities. |
| 4 |
* |
| 5 |
* @package gutenberg |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Sets an array in depth based on a path of keys. |
| 10 |
* |
| 11 |
* It is the PHP equivalent of JavaScript's `lodash.set()` and mirroring it may help other components |
| 12 |
* retain some symmetry between client and server implementations. |
| 13 |
* |
| 14 |
* Example usage: |
| 15 |
* |
| 16 |
* $array = array(); |
| 17 |
* _wp_array_set( $array, array( 'a', 'b', 'c', 1 ); |
| 18 |
* $array becomes: |
| 19 |
* array( |
| 20 |
* 'a' => array( |
| 21 |
* 'b' => array( |
| 22 |
* 'c' => 1, |
| 23 |
* ), |
| 24 |
* ), |
| 25 |
* ); |
| 26 |
* |
| 27 |
* @param array $array An array that we want to mutate to include a specific value in a path. |
| 28 |
* @param array $path An array of keys describing the path that we want to mutate. |
| 29 |
* @param mixed $value The value that will be set. |
| 30 |
*/ |
| 31 |
function gutenberg_experimental_set( &$array, $path, $value = null ) { |
| 32 |
// Confirm $array is valid. |
| 33 |
if ( ! is_array( $array ) ) { |
| 34 |
return; |
| 35 |
} |
| 36 |
|
| 37 |
// Confirm $path is valid. |
| 38 |
if ( ! is_array( $path ) ) { |
| 39 |
return; |
| 40 |
} |
| 41 |
$path_length = count( $path ); |
| 42 |
if ( 0 === $path_length ) { |
| 43 |
return; |
| 44 |
} |
| 45 |
foreach ( $path as $path_element ) { |
| 46 |
if ( |
| 47 |
! is_string( $path_element ) && ! is_integer( $path_element ) && |
| 48 |
! is_null( $path_element ) |
| 49 |
) { |
| 50 |
return; |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
for ( $i = 0; $i < $path_length - 1; ++$i ) { |
| 55 |
$path_element = $path[ $i ]; |
| 56 |
if ( |
| 57 |
! array_key_exists( $path_element, $array ) || |
| 58 |
! is_array( $array[ $path_element ] ) |
| 59 |
) { |
| 60 |
$array[ $path_element ] = array(); |
| 61 |
} |
| 62 |
$array = &$array[ $path_element ]; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.VariableRedeclaration |
| 63 |
} |
| 64 |
$array[ $path[ $i ] ] = $value; |
| 65 |
} |
| 66 |
|