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