Passed
Pull Request — master (#62)
by Sergei
01:55
created

SaveOrder::beforeMerge()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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