-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.php
108 lines (100 loc) · 2.94 KB
/
Parser.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
/**
* Qubus\Config
*
* @link https://github.com/QubusPHP/config
* @copyright 2020 Joshua Parker <josh@joshuaparker.blog>
* @copyright 2016 Sinergi
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types=1);
namespace Qubus\Config;
use function array_slice;
use function count;
use function current;
use function explode;
use function is_array;
class Parser
{
/**
* @param string $name
* @return array
*/
public static function getKey(string $name): array
{
$file = $key = $sub = null;
$parts = explode('.', $name);
if (isset($parts[0])) {
$file = $parts[0];
}
if (isset($parts[1])) {
$key = $parts[1];
}
if (isset($parts[2])) {
$sub = [];
foreach (array_slice($parts, 2) as $subkey) {
$sub[] = $subkey;
}
}
return [$file, $key, $sub];
}
/**
* @param array|null $haystack
* @param string|null $key
* @param null|array $sub
* @param null|mixed $default
* @return mixed
*/
public static function getValue(
?array $haystack = null,
?string $key = null,
?array $sub = null,
$default = null
): mixed {
if (empty($key) && ! isset($haystack)) {
return $default;
} elseif (empty($key)) {
if (! isset($haystack) && null !== $default) {
return $default;
} elseif (isset($haystack)) {
return $haystack;
}
return null;
} elseif (! empty($key) && empty($sub)) {
if (empty($haystack[$key]) && null !== $default) {
return $default;
} elseif (isset($haystack[$key])) {
return $haystack[$key];
}
return null;
} elseif (is_array($sub)) {
$array = $haystack[$key] ?? [];
$value = self::findInMultiArray($sub, $array);
if (empty($value) && null !== $default) {
return $default;
} elseif (isset($value)) {
return $value;
}
return null;
}
return null;
}
/**
* @param array $needle
* @param array $haystack
* @return mixed
*/
private static function findInMultiArray(array $needle, array $haystack): mixed
{
$currentNeedle = current($needle);
$needle = array_slice($needle, 1);
if (isset($haystack[$currentNeedle]) && is_array($haystack[$currentNeedle]) && count($needle)) {
return self::findInMultiArray($needle, $haystack[$currentNeedle]);
} elseif (isset($haystack[$currentNeedle]) && ! is_array($haystack[$currentNeedle]) && count($needle)) {
return null;
} elseif (isset($haystack[$currentNeedle])) {
return $haystack[$currentNeedle];
}
return null;
}
}