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
|
|
|
* This class provides methods to parse an array into a flatten array with key path separated by a delimiter. |
16
|
|
|
*/ |
17
|
|
|
class FlattenKeys |
18
|
|
|
{ |
19
|
2 |
|
public function __invoke(array $collection = [], string $delimiter = '.', bool $lowerKey = true): array |
20
|
|
|
{ |
21
|
2 |
|
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
|
2 |
|
public static function process(array $collection = [], string $delimiter = '.', bool $lowerKey = true, string $context = null): ?array |
30
|
|
|
{ |
31
|
2 |
|
$ret = []; |
32
|
|
|
|
33
|
2 |
|
foreach ($collection as $key => $value) { |
34
|
|
|
|
35
|
|
|
// flip value to key |
36
|
2 |
|
if (is_int($key)) { |
37
|
2 |
|
if (is_string($value)) { |
38
|
1 |
|
$key = $value; |
39
|
1 |
|
$value = true; |
40
|
|
|
} |
41
|
|
|
else { |
42
|
2 |
|
$key = null; |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
// force lower case key |
47
|
2 |
|
if (is_string($key)) { |
48
|
2 |
|
$key = trim($lowerKey ? mb_strtolower($key) : $key); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
// true for empty string |
52
|
2 |
|
if (is_string($value) && empty($value)) { |
53
|
|
|
$value = true; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
// set the key |
57
|
2 |
|
$currentKey = (!empty($context) ? $context . (!empty($key) ? $delimiter : null) : null) . $key; |
58
|
2 |
|
if (is_callable($value)) { |
59
|
1 |
|
$value = $value(); |
60
|
|
|
} |
61
|
|
|
|
62
|
2 |
|
if (is_array($value)) { |
63
|
2 |
|
$subRet = self::process($value, $delimiter, $lowerKey, $currentKey); |
64
|
2 |
|
if (is_array($subRet)) { |
65
|
2 |
|
$ret = array_merge_recursive($ret, $subRet); |
66
|
|
|
} |
67
|
|
|
|
68
|
2 |
|
if (!isset($ret[$currentKey])) { |
69
|
2 |
|
$ret[$currentKey] = false; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
else { |
73
|
2 |
|
$ret[$currentKey] = $value; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
2 |
|
return $ret; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|