ArrayUtil.php
5 years ago
DatabaseUtil.php
4 years ago
NumberUtil.php
5 years ago
StringUtil.php
5 years ago
ArrayUtil.php
72 lines
| 1 | <?php |
| 2 | /** |
| 3 | * A class of utilities for dealing with arrays. |
| 4 | */ |
| 5 | |
| 6 | namespace Automattic\WooCommerce\Utilities; |
| 7 | |
| 8 | /** |
| 9 | * A class of utilities for dealing with arrays. |
| 10 | */ |
| 11 | class ArrayUtil { |
| 12 | /** |
| 13 | * Get a value from an nested array by specifying the entire key hierarchy with '::' as separator. |
| 14 | * |
| 15 | * E.g. for [ 'foo' => [ 'bar' => [ 'fizz' => 'buzz' ] ] ] the value for key 'foo::bar::fizz' would be 'buzz'. |
| 16 | * |
| 17 | * @param array $array The array to get the value from. |
| 18 | * @param string $key The complete key hierarchy, using '::' as separator. |
| 19 | * @param mixed $default The value to return if the key doesn't exist in the array. |
| 20 | * |
| 21 | * @return mixed The retrieved value, or the supplied default value. |
| 22 | * @throws \Exception $array is not an array. |
| 23 | */ |
| 24 | public static function get_nested_value( array $array, string $key, $default = null ) { |
| 25 | $key_stack = explode( '::', $key ); |
| 26 | $subkey = array_shift( $key_stack ); |
| 27 | |
| 28 | if ( isset( $array[ $subkey ] ) ) { |
| 29 | $value = $array[ $subkey ]; |
| 30 | |
| 31 | if ( count( $key_stack ) ) { |
| 32 | foreach ( $key_stack as $subkey ) { |
| 33 | if ( is_array( $value ) && isset( $value[ $subkey ] ) ) { |
| 34 | $value = $value[ $subkey ]; |
| 35 | } else { |
| 36 | $value = $default; |
| 37 | break; |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | } else { |
| 42 | $value = $default; |
| 43 | } |
| 44 | |
| 45 | return $value; |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Checks if a given key exists in an array and its value can be evaluated as 'true'. |
| 50 | * |
| 51 | * @param array $array The array to check. |
| 52 | * @param string $key The key for the value to check. |
| 53 | * @return bool True if the key exists in the array and the value can be evaluated as 'true'. |
| 54 | */ |
| 55 | public static function is_truthy( array $array, string $key ) { |
| 56 | return isset( $array[ $key ] ) && $array[ $key ]; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Gets the value for a given key from an array, or a default value if the key doesn't exist in the array. |
| 61 | * |
| 62 | * @param array $array The array to get the value from. |
| 63 | * @param string $key The key to use to retrieve the value. |
| 64 | * @param null $default The default value to return if the key doesn't exist in the array. |
| 65 | * @return mixed|null The value for the key, or the default value passed. |
| 66 | */ |
| 67 | public static function get_value_or_default( array $array, string $key, $default = null ) { |
| 68 | return isset( $array[ $key ] ) ? $array[ $key ] : $default; |
| 69 | } |
| 70 | } |
| 71 | |
| 72 |