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