1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the Zemit Framework. |
5
|
|
|
* |
6
|
|
|
* (c) Zemit Team <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE.txt |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Zemit\Support\Helper\Arr; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* |
16
|
|
|
*/ |
17
|
|
|
class FlattenKeys |
18
|
|
|
{ |
19
|
|
|
public function __invoke(array $collection = [], string $delimiter = '.', bool $lowerKey = true): array |
20
|
|
|
{ |
21
|
|
|
return self::process($collection, $delimiter, $lowerKey); |
|
|
|
|
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Here to parse the columns parameter into some kind of flatten array with |
26
|
|
|
* the key path separated by dot "my.path" and the value true, false or a callback function |
27
|
|
|
* including the ExposeBuilder object |
28
|
|
|
*/ |
29
|
|
|
public static function process(array $collection = [], string $delimiter = '.', bool $lowerKey = true, string $context = null): ?array |
30
|
|
|
{ |
31
|
|
|
// nothing passed |
32
|
|
|
if (!isset($collection)) { |
33
|
|
|
return null; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
$ret = []; |
37
|
|
|
|
38
|
|
|
foreach ($collection as $key => $value) { |
39
|
|
|
|
40
|
|
|
// handle our special attribute |
41
|
|
|
if (is_bool($key)) { |
42
|
|
|
$value = $key; |
43
|
|
|
$key = null; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
// flip value to key |
47
|
|
|
if (is_int($key)) { |
48
|
|
|
if (is_string($value)) { |
49
|
|
|
$key = $value; |
50
|
|
|
$value = true; |
51
|
|
|
} |
52
|
|
|
else { |
53
|
|
|
$key = null; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
// force lower case key |
58
|
|
|
if (is_string($key)) { |
59
|
|
|
$key = trim($lowerKey ? mb_strtolower($key) : $key); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
// true for empty string |
63
|
|
|
if (is_string($value) && empty($value)) { |
64
|
|
|
$value = true; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
// set the key |
68
|
|
|
$currentKey = (!empty($context) ? $context . (!empty($key) ? $delimiter : null) : null) . $key; |
69
|
|
|
if (is_callable($value)) { |
70
|
|
|
$value = $value(); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
if (is_array($value)) { |
74
|
|
|
$subRet = self::process($value, $delimiter, $lowerKey, $currentKey); |
75
|
|
|
if (is_array($subRet)) { |
76
|
|
|
$ret = array_merge_recursive($ret, $subRet); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
if (!isset($ret[$currentKey])) { |
80
|
|
|
$ret[$currentKey] = false; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
else { |
84
|
|
|
$ret[$currentKey] = $value; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
return $ret; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|