Passed
Pull Request — master (#62)
by Sergei
12:43
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
use Yiisoft\Arrays\Collection\Modifier\ModifierInterface\AfterMergeModifierInterface;
9
use Yiisoft\Arrays\Collection\Modifier\ModifierInterface\BeforeMergeModifierInterface;
10
11
final class MergeWithKeysAsReverseMerge implements BeforeMergeModifierInterface, AfterMergeModifierInterface
12
{
13
    private array $array = [];
14
15
    public function beforeMerge(array $arrays, int $index): array
16
    {
17
        $this->array = $arrays[$index];
18
        return $this->array;
19
    }
20
21
    public function afterMerge(array $data): array
22
    {
23
        return $this->applyOrder($data, $this->array);
24
    }
25
26
    private function applyOrder(array $data, array $array): array
27
    {
28
        $result = [];
29
30
        foreach ($array as $key => $value) {
31
            if (is_string($key)) {
32
                if (array_key_exists($key, $data)) {
33
                    $result[$key] = ArrayHelper::remove($data, $key);
34
                }
35
            } else {
36
                foreach ($data as $dataKey => $dataValue) {
37
                    if (is_int($dataKey) && $dataValue === $value) {
38
                        $result[] = $dataValue;
39
                        unset($data[$dataKey]);
40
                        break;
41
                    }
42
                }
43
            }
44
45
            if (is_array($value) && is_array($result[$key])) {
46
                $result[$key] = $this->applyOrder($result[$key], $value);
47
            }
48
        }
49
50
        return array_merge($result, $data);
51
    }
52
}
53