Completed
Push — develop ( 540fdf...388072 )
by
unknown
02:38
created

ArrayService::findKeyChainsContainingKey()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 18
rs 9.2
ccs 0
cts 13
cp 0
cc 4
eloc 12
nc 4
nop 4
crap 20
1
<?php
2
3
/**
4
 * ArrayService
5
 */
6
7
namespace HDNET\OnpageIntegration\Service;
8
9
/**
10
 * Class ArrayService
11
 */
12
class ArrayService extends AbstractService
13
{
14
15
    /**
16
     * Replace a key $replaceKey with $replaceItem
17
     *
18
     * @param array $array
19
     * @param       $replaceItem
20
     * @param       $replaceKey
21
     *
22
     * @return array
23
     */
24 3
    public function replaceRecursiveByKey(array $array, $replaceItem, $replaceKey)
25
    {
26 3
        foreach ($array as $key => &$item) {
27 2
            if ($key === $replaceKey) {
28 2
                $item = $replaceItem;
29 2
            } elseif (is_array($item)) {
30 1
                $item = $this->replaceRecursiveByKey($item, $replaceItem, $replaceKey);
31 1
            }
32 3
        }
33 3
        return $array;
34
    }
35
36
    /**
37
     * @param array $array
38
     * @param string $searchKey
39
     * @return array
40
     */
41
    public function findByContainedKey(array $array, $searchKey)
42
    {
43
        $keyChains = $this->findKeyChainsContainingKey($array, $searchKey, [], []);
44
        $results   = [];
45
46
        foreach ($keyChains as $chain) {
47
            $results[] = implode('_', $chain);
48
        }
49
50
        return $results;
51
    }
52
53
    /**
54
     * @param array $array
55
     * @param string $searchKey
56
     * @param array $keyChains
57
     * @return array
58
     */
59
    protected function findKeyChainsContainingKey(array $array, $searchKey, array $keyChains, $keyChain)
60
    {
61
        foreach ($array as $key => $value) {
62
            if ($key !== $searchKey) {
63
                if (!is_array($value)){
64
                    continue;
65
                }
66
                $keyChain[] = $key;
67
                $keyChains  = $this->findKeyChainsContainingKey($value, $searchKey, $keyChains, $keyChain);
68
                array_pop($keyChain);
69
            } else {
70
                $keyChains[] = $keyChain;
71
                return $keyChains;
72
            }
73
        }
74
75
        return $keyChains;
76
    }
77
}
78