Passed
Push — master ( 4eb0b1...97a074 )
by Alexander
08:44 queued 07:18
created

InsertValueBeforeKey::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Arrays\Modifier;
6
7
/**
8
 * Inserts given value before specified key while performing {@see ArrayHelper::merge()}.
9
 *
10
 * The modifier should be specified as
11
 *
12
 * ```php
13
 * 'some-key' => new InsertValueBeforeKey('some-value', 'a-key-to-insert-before'),
14
 * ```
15
 *
16
 * ```php
17
 * $a = [
18
 *     'name' => 'Yii',
19
 *     'version' => '1.0',
20
 * ];
21
 *
22
 * $b = [
23
 *    'version' => '1.1',
24
 *    'options' => [],
25
 *    'vendor' => new InsertValueBeforeKey('Yiisoft', 'name'),
26
 * ];
27
 *
28
 * $result = ArrayHelper::merge($a, $b);
29
 * ```
30
 *
31
 * Will result in:
32
 *
33
 * ```php
34
 * [
35
 *     'vendor' => 'Yiisoft',
36
 *     'name' => 'Yii',
37
 *     'version' => '1.1',
38
 *     'options' => [],
39
 * ];
40
 */
41
final class InsertValueBeforeKey implements ModifierInterface
42
{
43
    /** @var mixed value of any type */
44
    private $value;
45
46
    private string $key;
47
48 1
    public function __construct($value, string $key)
49
    {
50 1
        $this->value = $value;
51 1
        $this->key = $key;
52 1
    }
53
54 1
    public function apply(array $data, $key): array
55
    {
56 1
        $res = [];
57 1
        foreach ($data as $k => $v) {
58 1
            if ($k === $this->key) {
59 1
                $res[$key] = $this->value;
60
            }
61 1
            $res[$k] = $v;
62
        }
63
64 1
        return $res;
65
    }
66
}
67