Passed
Pull Request — master (#62)
by Sergei
12:22
created

MergeWithKeysAsReverseMerge   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 19
c 1
b 0
f 0
dl 0
loc 40
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
B applyOrder() 0 25 9
A beforeMerge() 0 4 1
A afterMerge() 0 3 1
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