Completed
Push — master ( d7ccd4...e440d3 )
by Andre
01:55
created

Config::resolve()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 2
1
<?php
2
3
namespace TheIconic\Config;
4
5
class Config
6
{
7
    /**
8
     * @var array
9
     */
10
    protected $config = [];
11
12
    /**
13
     * @param array $config
14
     */
15
    public function __construct(array $config = [])
16
    {
17
        $this->config = $config;
18
    }
19
20
    /**
21
     * get the config value for a given key or the entire config if key is omitted
22
     * allows specifying a default that is used if key is not present in config
23
     *
24
     * @param string|null $key the config key
25
     * @param mixed|null $default the default value
26
     * @return array|mixed|null the config value or the entire configuration array
27
     */
28
    public function get($key = null, $default = null)
29
    {
30
        if (null === $key) {
31
            return $this->config;
32
        }
33
34
        return $this->resolve($key, $default);
35
    }
36
37
    /**
38
     * @param string $path
39
     * @param mixed|null $default
40
     * @return array|mixed|null
41
     */
42
    protected function resolve($path, $default = null)
43
    {
44
        $segments = explode('.', $path);
45
        $result = $this->config;
46
47
        foreach ($segments as $segment) {
48
            if (!isset($result[$segment])) {
49
                return $default;
50
            }
51
52
            $result = $result[$segment];
53
        }
54
55
        return $result;
56
    }
57
58
    /**
59
     * @param array|null $config
60
     * @return array
61
     */
62
    public function flatten(array $config = null): array
63
    {
64
        $flattened = [];
65
66
        if (null === $config) {
67
            $config = $this->config;
68
        }
69
70
        foreach ($config as $key => $value) {
71
            if (is_array($value)) {
72
                $tmp = $this->flatten($value);
73
74
                foreach ($tmp as $k => $v) {
75
                    $flattened[$key . '.' . $k] = $v;
76
                }
77
78
                continue;
79
            }
80
81
            $flattened[$key] = $value;
82
        }
83
84
        return $flattened;
85
    }
86
}