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

ReplaceValueWhole::beforeMerge()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 18
rs 9.6111
cc 5
nc 6
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Arrays\Collection\Modifier;
6
7
use Yiisoft\Arrays\ArrayHelper;
8
9
final class ReplaceValueWhole implements BeforeMergeModifierInterface
10
{
11
    /**
12
     * @var int|string
13
     */
14
    private $key;
15
16
    /**
17
     * @param int|string $key
18
     */
19
    public function __construct($key)
20
    {
21
        $this->key = $key;
22
    }
23
24
    /**
25
     * @param int|string $key
26
     * @return self
27
     */
28
    public function forKey($key): self
29
    {
30
        $new = clone $this;
31
        $new->key = $key;
32
        return $new;
33
    }
34
35
    public function beforeMerge(array $array, array $allArrays): array
36
    {
37
        if (!array_key_exists($this->key, $array)) {
38
            return $array;
39
        }
40
41
        $n = 0;
42
        foreach ($allArrays as $arr) {
43
            if (array_key_exists($this->key, $arr)) {
44
                $n++;
45
            }
46
            if ($n > 1) {
47
                ArrayHelper::remove($array, $this->key);
48
                return $array;
49
            }
50
        }
51
52
        return $array;
53
    }
54
}
55