-
Notifications
You must be signed in to change notification settings - Fork 30
/
get.php
57 lines (47 loc) · 1.46 KB
/
get.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
<?php
namespace Fuse\Helpers;
use function Fuse\Helpers\Types\{isArray, isNumber};
/**
* @return void
*/
function deepGet($obj, array $path, $index, &$list, &$arr)
{
if (is_null($obj)) {
return;
}
if (!isset($path[$index])) {
// If there's no path left, we've arrived at the object we care about.
$list[] = $obj;
} else {
$key = $path[$index];
$value = $obj[$key] ?? null;
if (is_null($value)) {
return;
}
// If we're at the last value in the path, and if it's a string/number/bool,
// add it to the list
if (
$index === sizeof($path) - 1 &&
(is_string($value) || isNumber($value) || is_bool($value))
) {
$list[] = is_bool($value) ? json_encode($value) : (string) $value;
} elseif (isArray($value)) {
$arr = true;
// Search each item in the array.
for ($i = 0, $len = sizeof($value); $i < $len; $i += 1) {
deepGet($value[$i], $path, $index + 1, $list, $arr);
}
} else {
// An object. Recurse further.
deepGet($value, $path, $index + 1, $list, $arr);
}
}
}
function get($obj, $path)
{
$list = [];
$arr = false;
// Backwards compatibility (since path used to be a string)
deepGet($obj, is_string($path) ? explode('.', $path) : $path, 0, $list, $arr);
return $arr ? $list : $list[0] ?? null;
}