Passed
Pull Request — master (#62)
by Sergei
06:40 queued 04:40
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
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