1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Honeybadger\Support; |
4
|
|
|
|
5
|
|
|
class Arr |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Determine whether the given value is array accessible. |
9
|
|
|
* |
10
|
|
|
* @param mixed $value |
11
|
|
|
* @return bool |
12
|
|
|
*/ |
13
|
|
|
public static function accessible($value) |
14
|
|
|
{ |
15
|
|
|
return is_array($value) || $value instanceof ArrayAccess; |
|
|
|
|
16
|
|
|
} |
17
|
|
|
/** |
18
|
|
|
* Get an item from an array using "dot" notation. |
19
|
|
|
* |
20
|
|
|
* @param \ArrayAccess|array $array |
21
|
|
|
* @param string $key |
22
|
|
|
* @param mixed $default |
23
|
|
|
* @return mixed |
24
|
|
|
*/ |
25
|
|
|
public static function get($array, $key, $default = null) |
26
|
|
|
{ |
27
|
|
|
if (! static::accessible($array)) { |
28
|
|
|
return $default; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
if (is_null($key)) { |
|
|
|
|
32
|
|
|
return $array; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
if (static::exists($array, $key)) { |
36
|
|
|
return $array[$key]; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
if (strpos($key, '.') === false) { |
40
|
|
|
return $array[$key] ?? $default; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
foreach (explode('.', $key) as $segment) { |
44
|
|
|
if (static::accessible($array) && static::exists($array, $segment)) { |
45
|
|
|
$array = $array[$segment]; |
46
|
|
|
} else { |
47
|
|
|
return $default; |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $array; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Determine if the given key exists in the provided array. |
56
|
|
|
* |
57
|
|
|
* @param \ArrayAccess|array $array |
58
|
|
|
* @param string|int $key |
59
|
|
|
* @return bool |
60
|
|
|
*/ |
61
|
|
|
public static function exists($array, $key) |
62
|
|
|
{ |
63
|
|
|
if ($array instanceof ArrayAccess) { |
64
|
|
|
return $array->offsetExists($key); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return array_key_exists($key, $array); |
|
|
|
|
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param array $array |
73
|
|
|
* @param callable $callback |
74
|
|
|
* @return array |
75
|
|
|
*/ |
76
|
|
|
public static function mapWithKeys(array $array, callable $callback) : array |
77
|
|
|
{ |
78
|
|
|
$newArray = []; |
79
|
|
|
|
80
|
|
|
foreach ($array as $key => $item) { |
81
|
|
|
$newArray[$key] = $callback($item, $key); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return $newArray; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|