ArrayUtil.php
1 year ago
DefaultLogger.php
1 year ago
JsonSerializable.php
1 year ago
Logger.php
1 year ago
StringUtil.php
1 year ago
TimeUnit.php
1 year ago
TimeUtil.php
1 year ago
TimeValue.php
1 year ago
UrlUtil.php
1 year ago
ArrayUtil.php
75 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WonderPush\Util; |
| 4 | |
| 5 | if (count(get_included_files()) === 1) { http_response_code(403); exit(); } // Prevent direct access |
| 6 | |
| 7 | /** |
| 8 | * Utility class for array manipulation. |
| 9 | */ |
| 10 | class ArrayUtil { |
| 11 | |
| 12 | /** |
| 13 | * Flattens nested non-associative arrays, without preserving keys. |
| 14 | * |
| 15 | * Return `array()` if a non array argument has been given. |
| 16 | * |
| 17 | * @param array $nestedArrays The nested arrays to flatten. |
| 18 | * @return array |
| 19 | */ |
| 20 | public static function flatten($nestedArrays) { |
| 21 | $result = array(); |
| 22 | |
| 23 | if (is_array($nestedArrays)) { |
| 24 | foreach($nestedArrays as $v) { |
| 25 | if (is_array($v)) { |
| 26 | $result = array_merge($result, self::flatten($v)); |
| 27 | } else { |
| 28 | $result[] = $v; |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | return $result; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Return a given array key if it `isset` or a default value. |
| 38 | * |
| 39 | * Note: Using `isset` implies that if the key is present according to `array_key_exists()` |
| 40 | * but is associated to the value `null`, the default value will be returned instead (which defaults to `null`). |
| 41 | * |
| 42 | * @param array $array The array to look into |
| 43 | * @param integer|string $key The desired key |
| 44 | * @param mixed $notSet The default value to return if the key is missing or its associated value is `null`. |
| 45 | * @return mixed |
| 46 | */ |
| 47 | public static function getIfSet($array, $key, $notSet = null) { |
| 48 | return isset($array[$key]) ? $array[$key] : $notSet; |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Utility function `!is_null()`. |
| 53 | * @param mixed $var |
| 54 | * @return boolean |
| 55 | * @see filterNulls() |
| 56 | */ |
| 57 | public static function is_not_null($var) { |
| 58 | return $var !== null; |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Filter null values from an array. |
| 63 | * |
| 64 | * This differs from `array_filter($array)` without callback in that a strict comparison is used for `null`, |
| 65 | * so `0`, `false`, `""`, `array()` and the like will not be filtered out. |
| 66 | * |
| 67 | * @param array $array |
| 68 | * @return array |
| 69 | */ |
| 70 | public static function filterNulls($array) { |
| 71 | return array_filter($array, '\WonderPush\Util\ArrayUtil::is_not_null'); |
| 72 | } |
| 73 | |
| 74 | } |
| 75 |