Completed
Push — master ( c6aea9...538fb8 )
by Flo
05:04 queued 02:10
created

Config::recursive()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
1
<?php
2
/**
3
 * Config.php
4
 *
5
 * @package Faulancer\Service
6
 * @author Florian Knapp <[email protected]>
7
 */
8
namespace Faulancer\Service;
9
10
use Faulancer\Exception\ConfigInvalidException;
11
12
/**
13
 * Represents a configuration array
14
 */
15
class Config
16
{
17
18
    /**
19
     * Holds the configuration data
20
     * @var array
21
     */
22
    protected $_config = [];
23
24
    protected $temp_conf = [];
25
26
    /**
27
     * Set configuration value by key
28
     *
29
     * @param string $key
30
     * @param mixed  $value
31
     * @param boolean $force
32
     * @return boolean
33
     * @throws ConfigInvalidException
34
     */
35
    public function set($key, $value = null, $force = false)
36
    {
37
        if (is_array($key) && $value === null) {
38
            foreach ($key as $k => $v) {
39
                $this->set($k, $v);
40
            }
41
            return true;
42
        }
43
44
        if ($force || empty($this->_config[$key])) {
45
            $this->_config[$key] = $value;
46
            return true;
47
        }
48
49
        throw new ConfigInvalidException();
50
    }
51
52
    /**
53
     * Get configuration value by key
54
     * @param string $key
55
     * @return mixed
56
     * @throws ConfigInvalidException
57
     */
58
    public function get($key)
59
    {
60
        if (strpos($key, ':') !== false) {
61
            return $this->recursive($key);
62
        }
63
64
        if (empty($this->_config[$key])) {
65
            throw new ConfigInvalidException('No value for key "' . $key . '" found.');
66
        }
67
68
        return $this->_config[$key];
69
    }
70
71
    /**
72
     * @param $key
73
     * @return array|mixed
74
     * @throws ConfigInvalidException
75
     */
76
    private function recursive($key)
77
    {
78
        $parts  = explode(':', $key);
79
        $result = $this->_config;
80
81
        foreach ($parts as $part) {
82
83
            if (empty($result[$part])) {
84
                return '';
85
            }
86
87
            $result = $result[$part];
88
        }
89
90
        return $result;
91
    }
92
93
}