Passed
Pull Request — master (#62)
by Sergei
12:43
created

ReplaceValueWhole::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
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\AfterMergeModifierInterface;
8
use Yiisoft\Arrays\Collection\Modifier\ModifierInterface\BeforeMergeModifierInterface;
9
10
final class ReplaceValueWhole implements BeforeMergeModifierInterface, AfterMergeModifierInterface
11
{
12
    /**
13
     * @var int|string
14
     */
15
    private $key;
16
17
    /**
18
     * @var mixed
19
     */
20
    private $value;
21
22
    private bool $setValueAfterMerge = false;
23
24
    /**
25
     * @param int|string $key
26
     */
27
    public function __construct($key)
28
    {
29
        $this->key = $key;
30
    }
31
32
    /**
33
     * @param int|string $key
34
     * @return self
35
     */
36
    public function forKey($key): self
37
    {
38
        $new = clone $this;
39
        $new->key = $key;
40
        return $new;
41
    }
42
43
    public function beforeMerge(array $arrays, int $index): array
44
    {
45
        $currentArray = $arrays[$index];
46
47
        if (!array_key_exists($this->key, $currentArray)) {
48
            return $arrays[$index];
49
        }
50
51
        foreach (array_slice($arrays, $index + 1) as $array) {
52
            if (array_key_exists($this->key, $array)) {
53
                $currentArray[$this->key] = null;
54
                return $currentArray;
55
            }
56
        }
57
58
        foreach (array_slice($arrays, 0, $index) as $array) {
59
            if (array_key_exists($this->key, $array)) {
60
                $this->value = $currentArray[$this->key];
61
                $this->setValueAfterMerge = true;
62
                return $currentArray;
63
            }
64
        }
65
66
        return $currentArray;
67
    }
68
69
    public function afterMerge(array $data): array
70
    {
71
        if ($this->setValueAfterMerge) {
72
            $data[$this->key] = $this->value;
73
            $this->setValueAfterMerge = false;
74
        }
75
        return $data;
76
    }
77
}
78