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

Merge   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 42
ccs 23
cts 23
cp 1
rs 10
c 0
b 0
f 0
wmc 12

5 Methods

Rating   Name   Duplication   Size   Complexity  
A mergeCurrentArrayValues() 0 8 3
A execute() 0 9 2
A canMergeArrayValue() 0 3 3
A mergeIntegerKeyValue() 0 6 2
A mergeNextArray() 0 4 2
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