Skip to content

Commit 686281d

Browse files
committed
fix: with: correct array uniqueness, preserve keys
1 parent 4b1b057 commit 686281d

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

src/Support/With.php

+16-5
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,28 @@ public static function wash(iterable $with): array
2727
->toArray();
2828
}
2929

30-
private static function uniqueRecursive($value)
30+
private static function uniqueRecursive($value): array
3131
{
3232
return array_map(static function ($value) {
3333
if (is_iterable($value)) {
34-
$value = collect($value)->all();
35-
$isAssoc = Arr::isAssoc($value);
36-
$value = array_unique($value, SORT_REGULAR);
37-
return self::uniqueRecursive($isAssoc ? $value : array_values($value));
34+
return self::uniqueRecursive(self::uniqueKeyPreserved(collect($value)->all()));
3835
}
3936

4037
return $value;
4138
}, collect($value)->all());
4239
}
40+
41+
private static function uniqueKeyPreserved(array $value): array
42+
{
43+
if (Arr::isAssoc($value)) {
44+
$entries = array_map(static fn($k, $v) => [$k, $v], array_keys($value), array_values($value));
45+
$entries = array_values(array_unique($entries, SORT_REGULAR));
46+
return array_combine(
47+
array_column($entries, 0),
48+
array_column($entries, 1)
49+
);
50+
}
51+
52+
return array_values(array_unique($value, SORT_REGULAR));
53+
}
4354
}

tests/Unit/Support/WithTest.php

+1
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ public function washProvider()
7575
[[], []],
7676
[[], ['foo' => []]],
7777
[['foo' => [1]], ['foo' => [1, 1, 1]]],
78+
[['foo' => ['a' => 1, 'b' => 1]], ['foo' => ['a' => 1, 'b' => 1]]],
7879
[
7980
[
8081
'included' => [['id' => 1, 'attributes' => []]]

0 commit comments

Comments
 (0)