Passed
Pull Request — master (#62)
by Sergei
06:40 queued 04:40
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
final class MoveValueBeforeKey implements DataModifierInterface
13
{
14
    /**
15
     * @var int|string
16
     */
17
    private $key;
18
19
    /**
20
     * @var int|string
21
     */
22
    private $beforeKey;
23
24
    /**
25
     * @param int|string $key
26
     * @param int|string $beforeKey
27
     */
28 4
    public function __construct($key, $beforeKey)
29
    {
30 4
        $this->key = $key;
31 4
        $this->beforeKey = $beforeKey;
32 4
    }
33
34
    /**
35
     * @param int|string $key
36
     * @return self
37
     */
38 1
    public function withKey($key): self
39
    {
40 1
        $new = clone $this;
41 1
        $new->key = $key;
42 1
        return $new;
43
    }
44
45
    /**
46
     * @param int|string $key
47
     * @return self
48
     */
49 1
    public function beforeKey($key): self
50
    {
51 1
        $new = clone $this;
52 1
        $new->beforeKey = $key;
53 1
        return $new;
54
    }
55
56 4
    public function apply(array $data): array
57
    {
58 4
        if (!array_key_exists($this->key, $data)) {
59 1
            return $data;
60
        }
61
62 3
        $result = [];
63 3
        foreach ($data as $k => $v) {
64 3
            if ($k === $this->beforeKey) {
65 3
                $result[$this->key] = $data[$this->key];
66
            }
67 3
            if ($k !== $this->key) {
68 3
                $result[$k] = $v;
69
            }
70
        }
71
72 3
        return $result;
73
    }
74
}
75