Passed
Push — master ( aec349...e9c1f2 )
by Alexander
04:11
created

InsertValueBeforeKey::apply()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 14
ccs 7
cts 7
cp 1
rs 10
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Composer\Config\Merger\Modifier;
6
7
/**
8
 * Inserts given value before specified key while performing {@see Merger::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 = Merger::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
    /**
49
     * @param mixed $value value of any type
50
     * @param string $key
51
     */
52 2
    public function __construct($value, string $key)
53
    {
54 2
        $this->value = $value;
55 2
        $this->key = $key;
56 2
    }
57
58 2
    public function apply(array $data, $key): array
59
    {
60 2
        $res = [];
61
        /** @psalm-var mixed $v */
62 2
        foreach ($data as $k => $v) {
63 2
            if ($k === $this->key) {
64
                /** @var mixed */
65 2
                $res[$key] = $this->value;
66
            }
67
            /** @var mixed */
68 2
            $res[$k] = $v;
69
        }
70
71 2
        return $res;
72
    }
73
}
74