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

InsertValueBeforeKey::setValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Arrays\Collection\Modifier;
6
7
final class InsertValueBeforeKey implements DataModifierInterface
8
{
9
    /**
10
     * @var int|string|null
11
     */
12
    private $key = null;
13
14
    /**
15
     * @var mixed
16
     */
17
    private $value = null;
18
19
    /**
20
     * @var int|string|null
21
     */
22
    private $beforeKey = null;
23
24
    /**
25
     * @param int|string $key
26
     * @return self
27
     */
28
    public function withKey($key): self
29
    {
30
        $new = clone $this;
31
        $new->key = $key;
32
        return $new;
33
    }
34
35
    /**
36
     * @param mixed $value
37
     * @return self
38
     */
39
    public function setValue($value): self
40
    {
41
        $new = clone $this;
42
        $new->value = $value;
43
        return $new;
44
    }
45
46
    /**
47
     * @param int|string $key
48
     * @return self
49
     */
50
    public function beforeKey($key): self
51
    {
52
        $new = clone $this;
53
        $new->beforeKey = $key;
54
        return $new;
55
    }
56
57
    public function apply(array $data): array
58
    {
59
        if ($this->key === null || $this->beforeKey === null) {
60
            return $data;
61
        }
62
63
        $result = [];
64
        foreach ($data as $k => $v) {
65
            if ($k === $this->beforeKey) {
66
                $result[$this->key] = $this->value;
67
            }
68
            $result[$k] = $v;
69
        }
70
71
        return $result;
72
    }
73
}
74