Merge   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 42
ccs 23
cts 23
cp 1
rs 10
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 34
    public function execute(... $arrays): array
18
    {
19 34
        $result = \array_shift($arrays);
20 34
        while (!empty($arrays)) {
21 34
            $nextArray = \array_shift($arrays);
22 34
            $this->mergeNextArray($nextArray, $result);
23
        }
24
25 34
        return $result;
26
    }
27
28 34
    private function mergeNextArray(array $nextArray, &$result): void
29
    {
30 34
        foreach ($nextArray as $key => $value) {
31 22
            $this->mergeCurrentArrayValues($key, $value, $result);
32
        }
33 34
    }
34
35 22
    private function mergeCurrentArrayValues($key, $value, &$result): void
36
    {
37 22
        if (\is_int($key)) {
38 12
            $this->mergeIntegerKeyValue($key, $value, $result);
39 12
        } elseif ($this->canMergeArrayValue($key, $value, $result)) {
40 6
            $result[$key] = $this->execute($result[$key], $value);
41
        } else {
42 11
            $result[$key] = $value;
43
        }
44 22
    }
45
46 12
    private function canMergeArrayValue($key, $value, $result): bool
47
    {
48 12
        return \is_array($value) && isset($result[$key]) && \is_array($result[$key]);
49
    }
50
51 12
    private function mergeIntegerKeyValue($key, $value, &$result): void
52
    {
53 12
        if (\array_key_exists($key, $result)) {
54 11
            $result[] = $value;
55
        } else {
56 4
            $result[$key] = $value;
57
        }
58 12
    }
59
}
60