Passed
Pull Request — master (#62)
by Sergei
13:28
created

InsertValueBeforeKey   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 19
c 1
b 0
f 0
dl 0
loc 41
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A apply() 0 11 3
A withKey() 0 5 1
A setValue() 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
final class InsertValueBeforeKey implements ModifierInterface
8
{
9
    private $key;
10
11
    private $value;
12
13
    private $beforeKey;
14
15
    public function withKey($key): self
16
    {
17
        $new = clone $this;
18
        $new->key = $key;
19
        return $new;
20
    }
21
22
    public function setValue($value): self
23
    {
24
        $new = clone $this;
25
        $new->value = $value;
26
        return $new;
27
    }
28
29
    public function beforeKey($key): self
30
    {
31
        $new = clone $this;
32
        $new->beforeKey = $key;
33
        return $new;
34
    }
35
36
37
    public function apply(array $data): array
38
    {
39
        $res = [];
40
        foreach ($data as $k => $v) {
41
            if ($k === $this->beforeKey) {
42
                $res[$this->key] = $this->value;
43
            }
44
            $res[$k] = $v;
45
        }
46
47
        return $res;
48
    }
49
}
50