Passed
Pull Request — master (#62)
by Sergei
13:01
created

MergeWithKeysAsReverseMerge::beforeMerge()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Arrays\Collection\Modifier;
6
7
use Yiisoft\Arrays\ArrayHelper;
8
9
final class MergeWithKeysAsReverseMerge implements BeforeMergeModifierInterface, DataModifierInterface
10
{
11
    private array $array = [];
12
13
    public function beforeMerge(array $array, array $allArrays): array
14
    {
15
        $this->array = $array;
16
        return $array;
17
    }
18
19
    public function apply(array $data): array
20
    {
21
        return $this->applyOrder($data, $this->array);
22
    }
23
24
    private function applyOrder(array $data, array $array): array
25
    {
26
        $result = [];
27
28
        foreach ($array as $key => $value) {
29
            if (is_string($key)) {
30
                if (array_key_exists($key, $data)) {
31
                    $result[$key] = ArrayHelper::remove($data, $key);
32
                }
33
            } else {
34
                foreach ($data as $dataKey => $dataValue) {
35
                    if (is_int($dataKey) && $dataValue === $value) {
36
                        $result[] = $dataValue;
37
                        unset($data[$dataKey]);
38
                        break;
39
                    }
40
                }
41
            }
42
43
            if (is_array($value) && is_array($result[$key])) {
44
                $result[$key] = $this->applyOrder($result[$key], $value);
45
            }
46
        }
47
48
        return array_merge($result, $data);
49
    }
50
}
51