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