-
-
Notifications
You must be signed in to change notification settings - Fork 383
/
Copy pathArrayParametersMerger.php
86 lines (73 loc) · 2.34 KB
/
ArrayParametersMerger.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
<?php
declare(strict_types=1);
namespace Rector\Core\Util;
final class ArrayParametersMerger
{
/**
* Merges configurations. Left has higher priority than right one.
*
* @autor David Grudl (https://davidgrudl.com)
* @source https://github.com/nette/di/blob/8eb90721a131262f17663e50aee0032a62d0ef08/src/DI/Config/Helpers.php#L31
*/
public function merge(mixed $left, mixed $right): mixed
{
if (is_array($left) && is_array($right)) {
return $this->mergeLeftToRightWithCallable(
$left,
$right,
fn ($leftValue, $rightValue) => $this->merge($leftValue, $rightValue)
);
}
if ($left !== null) {
return $left;
}
if (! is_array($right)) {
return $left;
}
return $right;
}
/**
* The same as above, just with the case if both values being non-array, it will combined them to array:
*
* $this->mergeWithCombine(1, 2); // [1, 2]
*/
public function mergeWithCombine(mixed $left, mixed $right): mixed
{
if (is_array($left) && is_array($right)) {
return $this->mergeLeftToRightWithCallable(
$left,
$right,
fn ($leftValue, $rightValue) => $this->mergeWithCombine($leftValue, $rightValue)
);
}
if ($left === null && is_array($right)) {
return $right;
}
if (! empty($right) && (array) $left !== (array) $right) {
return $this->mergeWithCombine((array) $right, (array) $left);
}
return $left;
}
/**
* @param array<int|string, mixed> $left
* @param array<int|string, mixed> $right
* @return mixed[]
*/
private function mergeLeftToRightWithCallable(array $left, array $right, callable $mergeCallback): array
{
foreach ($left as $key => $val) {
if (is_int($key)) {
// prevent duplicated values in unindexed arrays
if (! in_array($val, $right, true)) {
$right[] = $val;
}
} else {
if (isset($right[$key])) {
$val = $mergeCallback($val, $right[$key]);
}
$right[$key] = $val;
}
}
return $right;
}
}