Passed
Push — master ( fe8da9...4bb742 )
by Saulius
02:35
created

Merge::execute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 2
rs 9.6666
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the sauls/helpers package.
4
 *
5
 * @author    Saulius Vaičeliūnas <[email protected]>
6
 * @link      http://saulius.vaiceliunas.lt
7
 * @copyright 2018
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace Sauls\Component\Helper\Operation\ArrayOperation;
14
15
class Merge implements MergeInterface
16
{
17 29
    public function execute(... $arrays): array
18
    {
19 29
        $result = \array_shift($arrays);
20 29
        while (!empty($arrays)) {
21 29
            $nextArray = \array_shift($arrays);
22 29
            $this->mergeNextArray($nextArray, $result);
23
        }
24
25 29
        return $result;
26
    }
27
28 29
    private function mergeNextArray(array $nextArray, &$result): void
29
    {
30 29
        foreach ($nextArray as $key => $value) {
31 17
            $this->mergeCurrentArrayValues($key, $value, $result);
32
        }
33 29
    }
34
35 17
    private function mergeCurrentArrayValues($key, $value, &$result): void
36
    {
37 17
        if (\is_int($key)) {
38 9
            $this->mergeIntegerKeyValue($key, $value, $result);
39 10
        } elseif ($this->canMergeArrayValue($key, $value, $result)) {
40 5
            $result[$key] = $this->execute($result[$key], $value);
41
        } else {
42 9
            $result[$key] = $value;
43
        }
44 17
    }
45
46 10
    private function canMergeArrayValue($key, $value, $result): bool
47
    {
48 10
        return \is_array($value) && isset($result[$key]) && \is_array($result[$key]);
49
    }
50
51 9
    private function mergeIntegerKeyValue($key, $value, &$result): void
52
    {
53 9
        if (\array_key_exists($key, $result)) {
54 9
            $result[] = $value;
55
        } else {
56 3
            $result[$key] = $value;
57
        }
58 9
    }
59
}
60