Completed
Push — master ( 027d8f...567b7d )
by James Ekow Abaka
01:44
created

Config::__construct()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 10
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 4
nop 2
crap 20
1
<?php
2
3
namespace ntentan\config;
4
5
class Config 
6
{
7
8
    private $config;
9
    private $context = 'default';
10
11
    public function __construct($path = null, $namespace = null) {
12
        if (is_dir($path)) {
13
            $dir = new Directory($path);
14
            $this->config = ['default' => $this->expand($dir->parse(), $namespace)];
15
            foreach ($dir->getContexts() as $context) {
16
                $this->config[$context] = array_merge(
17
                        $this->config['default'], $this->expand($dir->parse($context), $namespace)
18
                );
19
            }
20
        } else if (is_file($path)) {
21
            $this->config[$this->context] = $this->expand(File::read($path), $namespace);
22
        }
23
    }
24
    
25
    public static function readDirectory($path, $namespace = null) {
26
        return new Config($path, $namespace);
27
    }
28
29
    public function isKeySet($key) {
30
        return isset($this->config[$this->context][$key]);
31
    }
32
33
    public function get($key) {
34
        return $this->config[$this->context][$key];
35
    }
36
37
    public function setContext($context) {
38
        $this->context = $context;
39
    }
40
41
    public function set($key, $value) {
42
        $keys = explode('.', $key);
43
        $this->config[$this->context] = $this->setValue($keys, $value, $this->config[$this->context]);
44
        $this->config[$this->context][$key] = $value;
45
        if (is_array($value)) {
46
            $this->config[$this->context] += $this->expand($value, null, $key);
47
        }
48
    }
49
50
    private function setValue($keys, $value, $config) {
51
        if (!empty($keys)) {
52
            $key = array_shift($keys);
53
            $config[$key] = $this->setValue($keys, $value, isset($config[$key]) ? $config[$key] : []);
54
            return $config;
55
        } else {
56
            return $value;
57
        }
58
    }
59
60
    private function expand($array, $namespace, $prefix = null) {
61
        $config = [];
62
        if (!is_array($array))
63
            return $config;
64
        $dottedNamespace = $namespace ? "$namespace:" : "";
65
        $dottedPrefix = $prefix ? "$prefix." : "";
66
        foreach ($array as $key => $value) {
67
            $newPrefix = $dottedNamespace . $dottedPrefix . $key;
68
            $config[$newPrefix] = $value;
69
            $config += $this->expand($value, null, $newPrefix);
70
        }
71
        if ($prefix)
72
            $config[$prefix] = $array;
73
        return $config;
74
    }
75
76
}
77