Completed
Push — master ( 39d639...38e886 )
by Oleg
04:40
created

MergeAttributes::merge()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6.0061

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 27
ccs 17
cts 18
cp 0.9444
rs 8.439
cc 6
eloc 14
nc 9
nop 0
crap 6.0061
1
<?php
2
namespace Malezha\Menu\Support;
3
4
class MergeAttributes
5
{
6
    /**
7
     * @var array
8
     */
9
    protected $arrays = [];
10
11
    /**
12
     * MergeAttributes constructor.
13
     */
14 8
    public function __construct()
15
    {
16 8
        $this->arrays = func_get_args();
17 8
    }
18
    
19
    /**
20
     * Merge array values as html attributes
21
     *
22
     * @return array
23
     */
24 8
    public function merge()
25
    {
26 8
        $arrays = $this->arrays;
27
28 8
        if (empty($arrays)) {
29
            return [];
30
        }
31
32 8
        $keys = [];
33 8
        foreach ($arrays as $array) {
34 8
            $keys = array_merge($keys, array_keys($array));
35 8
        }
36
37 8
        $keys = array_unique($keys);
38
39 8
        $merged = array_fill_keys($keys, null);
40
41 8
        foreach ($arrays as $array) {
42 8
            foreach ($keys as $key) {
43 7
                if (array_key_exists($key, $array)) {
44 7
                    $merged[$key] = $this->mergeValues($merged[$key], $array[$key]);
45 7
                }
46 8
            }
47 8
        }
48
49 8
        return $merged;
50
    }
51
    
52
    /**
53
     * @param string $valueOne
54
     * @param string $valueTwo
55
     * @return string
56
     */
57 7
    protected function mergeValues($valueOne, $valueTwo)
58
    {
59 7
        if (is_null($valueOne)) {
60 7
            return $valueTwo;
61
        }
62
        
63 2
        $valueOne = explode(' ', $valueOne);
64 2
        $valueTwo = explode(' ', $valueTwo);
65
66 2
        $merged = array_merge($valueOne, $valueTwo);
67
68 2
        return trim(implode(' ', $merged));
69
    }
70
}