Completed
Pull Request — develop (#57)
by Tony
06:12
created

Settings::recursive_keys()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
c 5
b 1
f 0
dl 0
loc 17
rs 9.2
cc 4
eloc 11
nc 6
nop 3
1
<?php
2
/*
3
 * Copyright (C) 2016 Tony Murray <[email protected]>
4
 * This program is free software: you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation, either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
12
 * GNU General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
 */
17
/**
18
 * Settings.php
19
 *
20
 * @package    LibreNMS
21
 * @author     Tony Murray <[email protected]>
22
 * @copyright  2016 Tony Murray
23
 * @license    @license http://opensource.org/licenses/GPL-3.0 GNU Public License v3 or later
24
 */
25
namespace App\Settings;
26
27
28
use App\Models\DbConfig;
29
use Cache;
30
use Config;
31
use DB;
32
use Illuminate\Contracts\Config\Repository as ConfigContract;  // adds the possibility to replace the default Config facade
33
34
class Settings implements ConfigContract
35
{
36
    private $cache_time;
37
    private $database;
38
39
    public function __construct()
40
    {
41
        $this->database = new DatabaseRepository(DB::connection(), 'config');
0 ignored issues
show
Unused Code introduced by
The call to DatabaseRepository::__construct() has too many arguments starting with \DB::connection().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
42
        $this->cache_time = env('CACHE_LIFETIME', 60);
43
    }
44
45
    public function set($key, $value = null)
46
    {
47
        if (is_array($value)) {
48
            $value = self::arrayToPath($value, $key);
0 ignored issues
show
Bug introduced by
It seems like $key defined by parameter $key on line 45 can also be of type array; however, App\Settings\Settings::arrayToPath() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
49
            foreach ($value as $k => $v) {
50
                $this->database->set($k, $v);
51
                Cache::put($k, $v, $this->cache_time);
52
            }
53
        }
54
        else {
55
            $this->database->set($key, $value);
56
            Cache::put($key, $value, $this->cache_time);
57
        }
58
        return $value;
59
    }
60
61
62
    public function get($key, $default = null)
63
    {
64
        // return value from cache or fetch it and return it
65
        return Cache::remember($key, $this->cache_time, function () use ($key, $default) {
66
            $value = $this->database->get($key, $default);
67
68
            if (is_array($value)) {
69
                $value = self::pathToArray($value, $key);
70
                $config = Config::get('config.' . $key, $default);
71
                if (!is_null($config)) {
72
                    $value = array_replace_recursive($config, $value);
73
                }
74
            }
75
            elseif (is_null($value)) {
76
                return Config::get('config.' . $key);
77
            }
78
79
            return $value;
80
        });
81
    }
82
83
    protected static function pathToArray($data, $prefix = "")
84
    {
85
        $tree = array();
86
        foreach ($data as $key => $value) {
87
            if (substr($key, 0, strlen($prefix)) == $prefix) {
88
                $key = substr($key, strlen($prefix));
89
            }
90
            $parts = explode('.', trim($key, '.'));
91
92
            $temp = &$tree;
93
            foreach ($parts as $part) {
94
                $temp = &$temp[$part];
95
            }
96
            $temp = $value;
97
            unset($temp);
98
        }
99
        return $tree;
100
    }
101
102
    public function has($key)
103
    {
104
        return (Cache::has($key) || Config::has($key) || $this->database->has($key));
105
    }
106
107
    public function forget($key)
108
    {
109
        $this->database->forget($key);
110
        Cache::forget($key);
111
    }
112
113
    public function all()
114
    {
115
        // no caching :(
116
        $config_settings = Config::all()['config'];
117
        $db_settings = self::pathToArray($this->database->all());
118
        return array_replace_recursive($config_settings, $db_settings);
119
    }
120
121
    /**
122
     * Prepend a value onto an array configuration value.
123
     *
124
     * @param  string $key
125
     * @param  mixed $value
126
     * @return void
127
     */
128
    public function prepend($key, $value)
129
    {
130
        // TODO: Implement prepend() method.S
131
    }
132
133
    /**
134
     * Push a value onto an array configuration value.
135
     *
136
     * @param  string $key
137
     * @param  mixed $value
138
     * @return void
139
     */
140
    public function push($key, $value)
141
    {
142
        // TODO: Implement push() method.
143
    }
144
145
    protected static function arrayToPath($array, $prefix = "")
146
    {
147
        return self::recursive_keys($array, $prefix);
148
    }
149
150
    private static function recursive_keys(array $array, $prefix = "", array $path = array())
151
    {
152
        if ($prefix != "") {
153
            $prefix = trim($prefix, '.') . '.';
154
        }
155
        $result = array();
156
        foreach ($array as $key => $val) {
157
            $currentPath = array_merge($path, array($key));
158
            if (is_array($val)) {
159
                $result = array_merge($result, self::recursive_keys($val, $prefix, $currentPath));
160
            }
161
            else {
162
                $result[$prefix . join('.', $currentPath)] = $val;
163
            }
164
        }
165
        return $result;
166
    }
167
168
}