Passed
Pull Request — master (#62)
by Alexander
07:46
created

MoveValueBeforeKey::withKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
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\Collection\Modifier\ModifierInterface\DataModifierInterface;
8
9
/**
10
 * Move element with a key `key` before an element with `beforeKey` key.
11
 *
12
 * Simple usage:
13
 *
14
 * ```php
15
 * $modifier = new MoveValueBeforeKey('a', 'c');
16
 *
17
 * // ['b' => 2, 'a' => 1, 'c' => 3]
18
 * $result = $modifier->apply(['a' => 1, 'b' => 2, 'c' => 3])
19
 * ```
20
 *
21
 * Usage with merge:
22
 *
23
 * ```php
24
 * $a = [
25
 *     'name' => 'Yii',
26
 *     'version' => '1.0',
27
 * ];
28
 * $b = new ArrayCollection(
29
 *     [
30
 *         'version' => '3.0',
31
 *         'options' => [],
32
 *         'vendor' => 'Yiisoft',
33
 *     ],
34
 *     new MoveValueBeforeKey('vendor', 'name')
35
 * );
36
 *
37
 * // [
38
 * //     'vendor' => 'Yiisoft',
39
 * //     'name' => 'Yii',
40
 * //     'version' => '3.0',
41
 * //     'options' => [],
42
 * // ],
43
 * $result = ArrayHelper::merge($a, $b);
44
 * ```
45
 */
46
final class MoveValueBeforeKey extends Modifier implements DataModifierInterface
47
{
48
    /**
49
     * @var int|string
50
     */
51
    private $key;
52
53
    /**
54
     * @var int|string
55
     */
56
    private $beforeKey;
57
58
    /**
59
     * @param int|string $key
60
     * @param int|string $beforeKey
61
     */
62 5
    public function __construct($key, $beforeKey)
63
    {
64 5
        $this->key = $key;
65 5
        $this->beforeKey = $beforeKey;
66 5
    }
67
68
    /**
69
     * @param int|string $key
70
     *
71
     * @return self
72
     */
73 1
    public function withKey($key): self
74
    {
75 1
        $new = clone $this;
76 1
        $new->key = $key;
77 1
        return $new;
78
    }
79
80
    /**
81
     * @param int|string $key
82
     *
83
     * @return self
84
     */
85 1
    public function beforeKey($key): self
86
    {
87 1
        $new = clone $this;
88 1
        $new->beforeKey = $key;
89 1
        return $new;
90
    }
91
92 5
    public function apply(array $data): array
93
    {
94 5
        if (!array_key_exists($this->key, $data)) {
95 1
            return $data;
96
        }
97
98 4
        $result = [];
99 4
        foreach ($data as $k => $v) {
100 4
            if ($k === $this->beforeKey) {
101 4
                $result[$this->key] = $data[$this->key];
102
            }
103 4
            if ($k !== $this->key) {
104 4
                $result[$k] = $v;
105
            }
106
        }
107
108 4
        return $result;
109
    }
110
}
111