Completed
Push — master ( 3c39ab...a4e4a7 )
by Park Jong-Hun
03:20
created

KeyGlue::glueLoop()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 4
nop 3
1
<?php
2
3
namespace Prob\ArrayUtil;
4
5
class KeyGlue
6
{
7
8
    private $glueCharacter = '.';
9
10
    /**
11
     * processing target array
12
     * @var array
13
     */
14
    private $array = [];
15
    private $glueKeys = [];
16
17
18
    public function setArray(array $array)
19
    {
20
        $this->array = $array;
21
    }
22
23
    public function setGlueCharacter($glueCharacter)
24
    {
25
        $this->glueCharacter = $glueCharacter;
26
    }
27
28
    public function glueOnlyKey()
29
    {
30
        $this->glueKeys = [];
31
32
        $this->glueLoop($this->array);
33
        return $this->glueKeys;
34
    }
35
36
    public function glueKeyAndContainValue()
37
    {
38
        $this->glueKeys = [];
39
40
        $this->glueLoop($this->array, false);
41
        return $this->glueKeys;
42
    }
43
44
    private function glueLoop(array $array, $isContaindOnlyKey = true, $prev = '')
45
    {
46
        foreach ($array as $key => $value) {
47
            $curr = $this->getCurrentGlueName($key, $prev);
48
49
            if ($this->hasChild($value)) {
50
                $this->glueLoop($value, $isContaindOnlyKey, $curr);
51
                continue;
52
            }
53
54
            if ($isContaindOnlyKey) {
55
                $this->glueKeys[] = $curr;
56
            } else {
57
                $this->glueKeys[$curr] = $value;
58
            }
59
        }
60
    }
61
62
    private function getCurrentGlueName($key, $prev)
63
    {
64
        return $prev !== ''
65
                ? $prev . $this->glueCharacter . $key
66
                : $key;
67
    }
68
69
    public static function hasChild($value)
70
    {
71
        return is_array($value) && count($value) > 0;
72
    }
73
}
74