-
Notifications
You must be signed in to change notification settings - Fork 0
/
DotAccess.php
70 lines (65 loc) · 1.66 KB
/
DotAccess.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
namespace dokuwiki\plugin\oauthnextcloud;
/**
* Dot notation access to arrays
*
* @see https://stackoverflow.com/a/39118759/172068
*/
class DotAccess
{
/**
* Get an item from an array using "dot" notation.
*
* @param \ArrayAccess|array $array
* @param string $key
* @param mixed $default
* @return mixed
*/
public static function get($array, $key, $default = null)
{
if (!static::accessible($array)) {
return $default;
}
if (is_null($key)) {
return $array;
}
if (static::exists($array, $key)) {
return $array[$key];
}
if (strpos($key, '.') === false) {
return $array[$key] ?? $default;
}
foreach (explode('.', $key) as $segment) {
if (static::accessible($array) && static::exists($array, $segment)) {
$array = $array[$segment];
} else {
return $default;
}
}
return $array;
}
/**
* Determine whether the given value is array accessible.
*
* @param mixed $value
* @return bool
*/
protected static function accessible($value)
{
return is_array($value) || $value instanceof \ArrayAccess;
}
/**
* Determine if the given key exists in the provided array.
*
* @param \ArrayAccess|array $array
* @param string|int $key
* @return bool
*/
protected static function exists($array, $key)
{
if ($array instanceof \ArrayAccess) {
return $array->offsetExists($key);
}
return array_key_exists($key, $array);
}
}