|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace FRZB\Component\RequestMapper\Helper; |
|
6
|
|
|
|
|
7
|
|
|
use JetBrains\PhpStorm\Immutable; |
|
8
|
|
|
|
|
9
|
|
|
/** @internal */ |
|
10
|
|
|
#[Immutable] |
|
11
|
|
|
final class ArrayHelper |
|
12
|
|
|
{ |
|
13
|
|
|
private function __construct() |
|
14
|
|
|
{ |
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
|
|
/** Flatten a multi-dimensional associative array with dots. */ |
|
18
|
|
|
public static function flatten(iterable $array, string $prepend = ''): array |
|
19
|
|
|
{ |
|
20
|
|
|
$results = []; |
|
21
|
|
|
|
|
22
|
|
|
foreach ($array as $key => $value) { |
|
23
|
|
|
if (\is_array($value) && !empty($value)) { |
|
24
|
|
|
$results = array_merge($results, self::flatten($value, $prepend.$key.'.')); |
|
25
|
|
|
} else { |
|
26
|
|
|
$results[$prepend.$key] = $value; |
|
27
|
|
|
} |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
return $results; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** Convert a flatten "dot" notation array into an expanded array. */ |
|
34
|
|
|
public static function unFlatten(iterable $array): array |
|
35
|
|
|
{ |
|
36
|
|
|
$results = []; |
|
37
|
|
|
|
|
38
|
|
|
foreach ($array as $key => $value) { |
|
39
|
|
|
self::set($results, $key, $value); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
return $results; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Set an array item to a given value using "dot" notation. |
|
47
|
|
|
* If no key is given to the method, the entire array will be replaced. |
|
48
|
|
|
*/ |
|
49
|
|
|
public static function set(iterable &$array, null|string|int $key, mixed $value): array |
|
50
|
|
|
{ |
|
51
|
|
|
if (null === $key) { |
|
52
|
|
|
return $array = $value; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
$keys = explode('.', $key); |
|
56
|
|
|
|
|
57
|
|
|
foreach ($keys as $i => $key) { |
|
58
|
|
|
if (1 === \count($keys)) { |
|
59
|
|
|
break; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
unset($keys[$i]); |
|
63
|
|
|
|
|
64
|
|
|
// If the key doesn't exist at this depth, we will just create an empty array |
|
65
|
|
|
// to hold the next value, allowing us to create the arrays to hold final |
|
66
|
|
|
// values at the correct depth. Then we'll keep digging into the array. |
|
67
|
|
|
if (!isset($array[$key]) || !\is_array($array[$key])) { |
|
68
|
|
|
$array[$key] = []; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
$array = &$array[$key]; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
$array[array_shift($keys)] = $value; |
|
75
|
|
|
|
|
76
|
|
|
return $array; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|