-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDotArrayFilter.php
50 lines (47 loc) · 1.48 KB
/
DotArrayFilter.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
<?php
namespace Snowair\Dotenv;
class DotArrayFilter
{
/**
* Expands a flat array to a nested array.
*
* For example, `['0.Foo.Bar' => 'Far']` becomes
* `[['Foo' => ['Bar' => 'Far']]]`.
*
* @param array $data Array of environment data
* @return array
*/
public function __invoke(array $environment)
{
$result = array();
foreach ($environment as $flat => $value) {
$keys = explode('.', $flat);
$keys = array_reverse($keys);
$child = array(
$keys[0] => $value
);
array_shift($keys);
foreach ($keys as $k) {
$child = array(
$k => $child
);
}
$stack = array(array($child, &$result));
while (!empty($stack)) {
foreach ($stack as $curKey => &$curMerge) {
foreach ($curMerge[0] as $key => &$val) {
$hasKey = !empty($curMerge[1][$key]);
if ($hasKey && (array)$curMerge[1][$key] === $curMerge[1][$key] && (array)$val === $val) {
$stack[] = array(&$val, &$curMerge[1][$key]);
} else {
$curMerge[1][$key] = $val;
}
}
unset($stack[$curKey]);
}
unset($curMerge);
}
}
return $result;
}
}