Passed
Pull Request — master (#62)
by Sergei
14:59
created

SaveOrder   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A beforeMerge() 0 4 1
B applyOrder() 0 25 9
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
/**
12
 * Modifier "Save Order"
13
 *
14
 * Модификатор запоминает порядок элементов в текущей коллекции и пытается его сохранить
15
 * при объединении массивов.
16
 */
17
final class SaveOrder implements BeforeMergeModifierInterface, AfterMergeModifierInterface
18
{
19
    private array $array = [];
20
21
    public function beforeMerge(array $arrays, int $index): array
22
    {
23
        $this->array = $arrays[$index];
24
        return $this->array;
25
    }
26
27
    public function afterMerge(array $data): array
28
    {
29
        return $this->applyOrder($data, $this->array);
30
    }
31
32
    private function applyOrder(array $data, array $array): array
33
    {
34
        $result = [];
35
36
        foreach ($array as $key => $value) {
37
            if (is_string($key)) {
38
                if (array_key_exists($key, $data)) {
39
                    $result[$key] = ArrayHelper::remove($data, $key);
40
                }
41
            } else {
42
                foreach ($data as $dataKey => $dataValue) {
43
                    if (is_int($dataKey) && $dataValue === $value) {
44
                        $result[] = $dataValue;
45
                        unset($data[$dataKey]);
46
                        break;
47
                    }
48
                }
49
            }
50
51
            if (is_array($value) && is_array($result[$key])) {
52
                $result[$key] = $this->applyOrder($result[$key], $value);
53
            }
54
        }
55
56
        return array_merge($result, $data);
57
    }
58
}
59