Passed
Pull Request — master (#62)
by Sergei
20:57 queued 05:54
created

InsertValueBeforeKey   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
dl 0
loc 61
rs 10
c 1
b 0
f 0
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A apply() 0 17 5
A withKey() 0 5 1
A beforeKey() 0 5 1
A __construct() 0 4 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
 * This modifier inserts a value before the key given.
11
 */
12
final class InsertValueBeforeKey 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
    public function __construct($key, $beforeKey)
29
    {
30
        $this->key = $key;
31
        $this->beforeKey = $beforeKey;
32
    }
33
34
    /**
35
     * @param int|string $key
36
     * @return self
37
     */
38
    public function withKey($key): self
39
    {
40
        $new = clone $this;
41
        $new->key = $key;
42
        return $new;
43
    }
44
45
    /**
46
     * @param int|string $key
47
     * @return self
48
     */
49
    public function beforeKey($key): self
50
    {
51
        $new = clone $this;
52
        $new->beforeKey = $key;
53
        return $new;
54
    }
55
56
    public function apply(array $data): array
57
    {
58
        if (!array_key_exists($this->key, $data)) {
59
            return $data;
60
        }
61
62
        $result = [];
63
        foreach ($data as $k => $v) {
64
            if ($k === $this->beforeKey) {
65
                $result[$this->key] = $data[$this->key];
66
            }
67
            if ($k !== $this->key) {
68
                $result[$k] = $v;
69
            }
70
        }
71
72
        return $result;
73
    }
74
}
75