Config::get()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Garden;
4
5
/**
6
 * Application configuration management.
7
 *
8
 * This class provides access to the application configuration information through one or more config files.
9
 * You can load/save config files in several formats. The file extension of the file determines what format will the file will use.
10
 * The following file formats are supported.
11
 *
12
 * - javascript object notation (json): .json or .json.php
13
 * - php source code: .php
14
 * - php serialized arrays: .ser or .ser.php
15
 * - yaml: .yml or .yml.php
16
 *
17
 * When using config files we recommend always using the .*.php extension so that the file cannot be read through its url.
18
 *
19
 * @author Todd Burry <[email protected]>
20
 * @copyright 2009 Vanilla Forums Inc.
21
 * @license LGPL-2.1
22
 * @package Vanilla
23
 * @since 1.0
24
 */
25
class Config {
26
    /// Properties ///
27
28
    /**
29
     * @var array The config data.
30
     */
31
    protected static $data = [];
32
33
    /**
34
     * @var string The default path to load/save to.
35
     */
36
    protected static $defaultPath;
37
38
    /// Methods ///
39
40
    /**
41
     * Get or set the default path.
42
     *
43
     * @param string $value Pass a value to set a new default path.
44
     * @return string Returns the current default path.
45
     */
46
    public static function defaultPath($value = '') {
47
        if ($value) {
48
            self::$defaultPath = $value;
49
        } elseif (!self::$defaultPath) {
50
            self::$defaultPath = PATH_ROOT.'/conf/config.json.php';
51
        }
52
        return self::$defaultPath;
53
    }
54
55
    /**
56
     * Return all of the config data.
57
     *
58
     * @return array Returns an array of config data.
59
     */
60
    public static function data() {
61
        return self::$data;
62
    }
63
64
    /**
65
     * Get a setting from the config.
66
     *
67
     * @param string $key The config key.
68
     * @param mixed $default The default value if the config file doesn't exist.
69
     * @return mixed The value at {@link $key} or {@link $default} if the key isn't found.
70
     * @see \config()
71
     */
72
    public static function get($key, $default = null) {
73
        if (array_key_exists($key, self::$data)) {
74
            return self::$data[$key];
75
        } else {
76
            return $default;
77
        }
78
    }
79
80
    /**
81
     * Encode an array in ini format.
82
     * The resulting array will work with parse_ini_file() and parse_ini_string().
83
     *
84
     * @param array $data A flat, associative array of data.
85
     * @return string The data in ini format.
86
     */
87
//    public static function iniEncode($data) {
88
//        ksort($data, SORT_NATURAL | SORT_FLAG_CASE);
89
//
90
//        $result = '';
91
//
92
//        $lastSection = null;
93
//
94
//        foreach ($data as $key => $value) {
95
//            $section = trim(strstr($key, '.', true), '.');
96
//
97
//            if ($section !== $lastSection) {
98
//                if ($section) {
99
//                    $result .= "\n[$section]\n";
100
//                }
101
//                $lastSection = $section;
102
//            }
103
//
104
//            $result .= $key . ' = ';
105
//
106
//            if (is_bool($value)) {
107
//                $str = $value ? 'true' : 'false';
108
//            } elseif (is_numeric($value)) {
109
//                $str = $value;
110
//            } elseif (is_string($value)) {
111
//                $str = '"' . addcslashes($value, "\"") . '"';
112
//            }
113
//            $result .= $str . "\n";
114
//        }
115
//
116
//        return $result;
117
//    }
118
119
    /**
120
     * Load configuration data from a file.
121
     *
122
     * @param string $path An optional path to load the file from.
123
     * @param string $path If true the config will be put under the current config, not over it.
124
     * @param string $php_var The name of the php variable to load from if using the php file type.
125
     */
126
    public static function load($path = '', $underlay = false, $php_var = 'config') {
127
        if (!$path) {
128
            $path = self::$defaultPath;
129
        }
130
131
        $loaded = array_load($path, $php_var);
132
133
        if (empty($loaded)) {
134
            return;
135
        }
136
137
        if (!is_array(self::$data)) {
138
            self::$data = [];
139
        }
140
141
        if ($underlay) {
142
            self::$data = array_replace($loaded, self::$data);
143
        } else {
144
            self::$data = array_replace(self::$data, $loaded);
145
        }
146
    }
147
148
    /**
149
     * Save data to the config file.
150
     *
151
     * @param array $data The config data to save.
152
     * @param string $path An optional path to save the data to.
153
     * @param string $php_var The name of the php variable to load from if using the php file type.
154
     * @return bool Returns true if the save was successful or false otherwise.
155
     * @throws \InvalidArgumentException Throws an exception when the saved data isn't an array.
156
     */
157
    public static function save($data, $path = null, $php_var = 'config') {
158
        if (!is_array($data)) {
159
            throw new \InvalidArgumentException('Config::save(): Argument #1 is not an array.', 400);
160
        }
161
162
        if (!$path) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $path of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
163
            $path = static::defaultPath();
164
        }
165
166
        // Load the current config information so we know what to replace.
167
        $config = array_load($path, $php_var);
168
        // Merge the new config into the current config.
169
        $config = array_replace($config, $data);
170
        // Remove null config values.
171
        $config = array_filter($config, function ($value) {
172
            return $value !== null;
173
        });
174
175
        ksort($config, SORT_NATURAL | SORT_FLAG_CASE);
176
177
        $result = array_save($config, $path, $php_var);
178
        return $result;
179
    }
180
}
181