Completed
Push — master ( ccbb0b...5e3345 )
by Andre
02:09
created

Config::flatten()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 6
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
     * @param string $prefix
61
     * @return array
62
     */
63
    public function flatten(array $config = null, $prefix = ''): array
64
    {
65
        $flattened = [];
66
67
        if (null === $config) {
68
            $config = $this->config;
69
        }
70
71
        foreach ($config as $key => $value) {
72
            if (is_array($value)) {
73
                $flattened += $this->flatten($value, $prefix . $key . '.');
74
                continue;
75
            }
76
77
            $flattened[$prefix . $key] = $value;
78
        }
79
80
        return $flattened;
81
    }
82
}
83