Passed
Push — master ( beabee...313346 )
by Darío
03:23
created

ArrayDimension::ifdef()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 5
nop 3
dl 0
loc 15
rs 9.6111
c 0
b 0
f 0
1
<?php
2
/**
3
 * DronePHP (http://www.dronephp.com)
4
 *
5
 * @link      http://github.com/Pleets/DronePHP
6
 * @copyright Copyright (c) 2016-2018 Pleets. (http://www.pleets.org)
7
 * @license   http://www.dronephp.com/license
8
 * @author    Darío Rivera <[email protected]>
9
 */
10
11
namespace Drone\Util;
12
13
/**
14
 * ArrayDimension class
15
 *
16
 * Utils functions to operate arrays
17
 */
18
class ArrayDimension
19
{
20
    /**
21
     * Converts a multidimensional array in a dimensional array
22
     *
23
     * @param array  $array
24
     * @param string $glue
25
     *
26
     * @return array
27
     */
28
    public static function toUnidimensional(Array $array, $glue)
29
    {
30
        $new_config = [];
31
        $again = false;
32
33
        foreach ($array as $param => $configure)
34
        {
35
            if (is_array($configure))
36
            {
37
                foreach ($configure as $key => $value)
38
                {
39
                    $again = true;
40
                    $new_config[$param . $glue . $key] = $value;
41
                }
42
            }
43
            else
44
                $new_config[$param] = $configure;
45
        }
46
47
        return (!$again) ? $new_config : self::toUnidimensional($new_config, $glue);
48
    }
49
50
    /**
51
     * Search inside a multi-dimensional array some key
52
     *
53
     * Default value will be returned if any key in the array does not exists in any level
54
     *
55
     * @param array $needle
56
     * @param array $haystack
57
     * @param mixed $value
58
     *
59
     * @return mixed
60
     */
61
    public static function ifdef(array $needle, array $haystack, $value)
62
    {
63
        $key = array_shift($needle);
64
65
        do
66
        {
67
            if (array_key_exists($key, $haystack))
68
                $haystack = $haystack[$key];
69
            else
70
                return $value;
71
72
            $key = count($needle) ? array_shift($needle) : NULL;
73
74
            if (is_null($key))
75
                return $haystack;
76
77
        } while (!is_null($key));
78
    }
79
}