Completed
Push — master ( c2f0e4...194f59 )
by James Ekow Abaka
02:04
created

Data::expand()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

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