Passed
Pull Request — master (#62)
by Sergei
15:45 queued 49s
created

SaveOrder::afterMerge()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
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
 * Remembers the order of elements in the collection it is applied to
13
 * and tried to keep the order while merging.
14
 */
15
final class SaveOrder implements BeforeMergeModifierInterface, AfterMergeModifierInterface
16
{
17
    private array $array = [];
18
19
    private bool $nested = false;
20
21
    public function nested(): self
22
    {
23
        $new = clone $this;
24
        $new->nested = true;
25
        return $new;
26
    }
27
28
    public function notNested(): self
29
    {
30
        $new = clone $this;
31
        $new->nested = false;
32
        return $new;
33
    }
34
35
    public function beforeMerge(array $arrays, int $index): array
36
    {
37
        $this->array = $arrays[$index];
38
        return $this->array;
39
    }
40
41
    public function afterMerge(array $data): array
42
    {
43
        return $this->applyOrder($data, $this->array);
44
    }
45
46
    private function applyOrder(array $data, array $array): array
47
    {
48
        $result = [];
49
50
        foreach ($array as $key => $value) {
51
            if (is_string($key)) {
52
                if (array_key_exists($key, $data)) {
53
                    $result[$key] = ArrayHelper::remove($data, $key);
54
                }
55
            } else {
56
                foreach ($data as $dataKey => $dataValue) {
57
                    if (is_int($dataKey) && $dataValue === $value) {
58
                        $result[] = $dataValue;
59
                        unset($data[$dataKey]);
60
                        break;
61
                    }
62
                }
63
            }
64
65
            if ($this->nested && is_array($value) && is_array($result[$key])) {
66
                $result[$key] = $this->applyOrder($result[$key], $value);
67
            }
68
        }
69
70
        return array_merge($result, $data);
71
    }
72
}
73