Passed
Pull Request — master (#62)
by Sergei
19:21 queued 04:24
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
 * Modifier "Insert Value Before Key".
11
 *
12
 * Перемещает элемент с ключом "key" на позицию перед элементом с ключом "beforeKey".
13
 */
14
final class InsertValueBeforeKey implements DataModifierInterface
15
{
16
    /**
17
     * @var int|string
18
     */
19
    private $key;
20
21
    /**
22
     * @var int|string
23
     */
24
    private $beforeKey;
25
26
    /**
27
     * @param int|string $key
28
     * @param int|string $beforeKey
29
     */
30
    public function __construct($key, $beforeKey)
31
    {
32
        $this->key = $key;
33
        $this->beforeKey = $beforeKey;
34
    }
35
36
    /**
37
     * @param int|string $key
38
     * @return self
39
     */
40
    public function withKey($key): self
41
    {
42
        $new = clone $this;
43
        $new->key = $key;
44
        return $new;
45
    }
46
47
    /**
48
     * @param int|string $key
49
     * @return self
50
     */
51
    public function beforeKey($key): self
52
    {
53
        $new = clone $this;
54
        $new->beforeKey = $key;
55
        return $new;
56
    }
57
58
    public function apply(array $data): array
59
    {
60
        if (!array_key_exists($this->key, $data)) {
61
            return $data;
62
        }
63
64
        $result = [];
65
        foreach ($data as $k => $v) {
66
            if ($k === $this->beforeKey) {
67
                $result[$this->key] = $data[$this->key];
68
            }
69
            if ($k !== $this->key) {
70
                $result[$k] = $v;
71
            }
72
        }
73
74
        return $result;
75
    }
76
}
77