Config::_recursive()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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