Completed
Pull Request — master (#16)
by Flo
07:29
created

Config::get()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 12
rs 9.4285
c 1
b 0
f 1
cc 3
eloc 6
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
    /**
25
     * Set configuration value by key
26
     *
27
     * @param mixed   $key
28
     * @param mixed   $value
29
     * @param boolean $force
30
     * @return boolean
31
     * @throws ConfigInvalidException
32
     */
33
    public function set($key, $value = null, $force = false)
34
    {
35
        if (is_array($key) && $value === null) {
36
            foreach ($key as $k => $v) {
37
                $this->set($k, $v);
38
            }
39
            return true;
40
        }
41
42
        if ($force || empty($this->_config[$key])) {
43
            $this->_config[$key] = $value;
44
            return true;
45
        }
46
47
        throw new ConfigInvalidException();
48
    }
49
50
    /**
51
     * Get configuration value by key
52
     *
53
     * @param string $key
54
     * @return mixed
55
     * @throws ConfigInvalidException
56
     */
57
    public function get($key)
58
    {
59
        if (strpos($key, ':') !== false) {
60
            return $this->recursive($key);
61
        }
62
63
        if (!isset($this->_config[$key])) {
64
            throw new ConfigInvalidException('No value for key "' . $key . '" found.');
65
        }
66
67
        return $this->_config[$key];
68
    }
69
70
    /**
71
     * @param $key
72
     * @return bool
73
     */
74
    public function delete($key)
75
    {
76
        if (isset($this->_config[$key])) {
77
            unset($this->_config[$key]);
78
        }
79
        return true;
80
    }
81
82
    /**
83
     * Iterate through configuration till given key is found
84
     *
85
     * @param $key
86
     * @return array|mixed
87
     * @throws ConfigInvalidException
88
     */
89
    private function recursive($key)
90
    {
91
        $parts  = explode(':', $key);
92
        $result = $this->_config;
93
94
        foreach ($parts as $part) {
95
96
            if (empty($result[$part])) {
97
                return '';
98
            }
99
100
            $result = $result[$part];
101
        }
102
103
        return $result;
104
    }
105
106
}