Passed
Pull Request — master (#62)
by Sergei
02:11
created

MoveValueBeforeKey   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 61
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A apply() 0 17 5
A __construct() 0 4 1
A withKey() 0 5 1
A beforeKey() 0 5 1
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
     * @return self
71
     */
72 1
    public function withKey($key): self
73
    {
74 1
        $new = clone $this;
75 1
        $new->key = $key;
76 1
        return $new;
77
    }
78
79
    /**
80
     * @param int|string $key
81
     * @return self
82
     */
83 1
    public function beforeKey($key): self
84
    {
85 1
        $new = clone $this;
86 1
        $new->beforeKey = $key;
87 1
        return $new;
88
    }
89
90 5
    public function apply(array $data): array
91
    {
92 5
        if (!array_key_exists($this->key, $data)) {
93 1
            return $data;
94
        }
95
96 4
        $result = [];
97 4
        foreach ($data as $k => $v) {
98 4
            if ($k === $this->beforeKey) {
99 4
                $result[$this->key] = $data[$this->key];
100
            }
101 4
            if ($k !== $this->key) {
102 4
                $result[$k] = $v;
103
            }
104
        }
105
106 4
        return $result;
107
    }
108
}
109