Passed
Push — master ( b4a69d...029b26 )
by Harry
02:37
created

ArrayMerger::merge()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 2
dl 0
loc 15
ccs 11
cts 11
cp 1
crap 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Graze\ArrayMerger;
4
5
use Graze\ArrayMerger\ValueMerger\LastValue;
6
7
/**
8
 * Class ArrayMerger
9
 *
10
 * This does a simple, `array_merge`, but you can choose how to merge the values yourself
11
 */
12
class ArrayMerger implements ArrayMergerInterface
13
{
14
    use MergeHelpersTrait;
15
16
    /** @var callable */
17
    protected $valueMerger;
18
19
    /**
20
     * @param callable $valueMerger
21
     * @param int      $flags
22
     */
23 19
    public function __construct(callable $valueMerger = null, $flags = 0)
24
    {
25 19
        $this->valueMerger = $valueMerger ?: new LastValue();
26 19
        $this->flags = $flags;
27 19
    }
28
29
    /**
30
     * Merge using the supplied Value Merge
31
     *
32
     * @param callable $valueMerger
33
     * @param array    $array1
34
     * @param array    $arrays
35
     *
36
     * @return array
37
     */
38 9
    public static function mergeUsing(callable $valueMerger, array $array1, array $arrays)
39
    {
40 9
        $merger = new static($valueMerger);
41 9
        return call_user_func_array([$merger, 'merge'], array_merge([$array1], array_slice(func_get_args(), 2)));
42
    }
43
44
    /**
45
     * Merge the values from all the array supplied, the first array is treated as the base array to merge into
46
     *
47
     * @param array      $array1
48
     * @param array|null $arrays
49
     *
50
     * @return array
51
     */
52 19
    public function merge(array $array1, array $arrays = null)
53
    {
54 19
        list($merged, $arrays) = $this->checkSimpleMerge($array1, array_slice(func_get_args(), 1));
55
56 19
        foreach ($arrays as $toMerge) {
57 17
            foreach ($toMerge as $key => &$value) {
58 17
                if (array_key_exists($key, $merged)) {
59 17
                    $merged[$key] = call_user_func($this->valueMerger, $merged[$key], $value);
60 17
                } else {
61 2
                    $merged[$key] = $value;
62
                }
63 17
            }
64 19
        }
65
66 19
        return $merged;
67
    }
68
}
69