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

SaveOrder::applyOrder()   B

Complexity

Conditions 9
Paths 11

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 14
nc 11
nop 2
dl 0
loc 25
rs 8.0555
c 0
b 0
f 0
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