Completed
Push — master ( a4e4a7...e9fb92 )
by Park Jong-Hun
03:08
created

KeyGlue::isNumbericIndexdArray()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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