-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConfig.php
More file actions
320 lines (267 loc) · 8.22 KB
/
Config.php
File metadata and controls
320 lines (267 loc) · 8.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
<?php
/**
* @author Marwan Al-Soltany <[email protected]>
* @copyright Marwan Al-Soltany 2021
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace MAKS\Velox\Backend;
use MAKS\Velox\App;
use MAKS\Velox\Backend\Event;
use MAKS\Velox\Helper\Misc;
/**
* A class that loads everything from the "/config" directory and make it as an array that is accessible via dot-notation.
*
* Example:
* ```
* // get the entire config
* $entireConfig = Config::getAll();
*
* // check for config value availability
* $varNameExists = Config::has('filename.config.varName');
*
* // get a specific config value or fall back to a default value
* $varName = Config::get('filename.config.varName', 'fallbackValue');
*
* // set a specific config value at runtime
* Config::set('filename.config.varName', 'varValue');
*
* // delete cached config
* Config::clearCache();
* ```
*
* @package Velox\Backend
* @since 1.0.0
* @api
*/
class Config
{
/**
* This event will be dispatched when the config is loaded.
* This event will be passed a reference to the config array.
*
* @var string
*/
public const ON_LOAD = 'config.on.load';
/**
* This event will be dispatched when the config is cached.
* This event will not be passed any arguments.
*
* @var string
*/
public const ON_CACHE = 'config.on.cache';
/**
* This event will be dispatched when the config cache is cleared.
* This event will not be passed any arguments.
*
* @var string
*/
public const ON_CLEAR_CACHE = 'config.on.clearCache';
/**
* The default directory of the configuration files.
*
* @var string
*/
public const CONFIG_DIR = BASE_PATH . '/config';
/**
* The path of the cached configuration file.
*
* @var string
*/
public const CONFIG_CACHE_FILE = BASE_PATH . '/storage/cache/config/config.json';
/**
* The currently loaded configuration.
*/
protected static array $config;
public function __construct()
{
$this->load();
}
public function __toString()
{
return static::CONFIG_DIR;
}
/**
* Includes all files in a directory.
*
* @param string $path
*
* @return array
*/
private static function include(string $path): array
{
$includes = [];
$include = static function ($file) {
if (is_file($file)) {
$info = pathinfo($file);
return $info['extension'] == 'php' ? include($file) : [];
}
return self::include($file);
};
// load all config files
$filenames = scandir($path) ?: [];
foreach ($filenames as $filename) {
$file = sprintf('%s/%s', $path, $filename);
$config = basename($filename, '.php');
// do not include items that have dots in their names
// as this will conflict with array access separator
if (strpos($config, '.') !== false) {
continue;
}
$includes[$config] = isset($includes[$config])
? $include($file) + (array)$includes[$config]
: $include($file);
}
return $includes;
}
/**
* Parses the configuration to replace reference of some `{filename.config.varName}` with actual value from the passed configuration.
*
* @param array $config
*
* @return array
*/
private static function parse(array $config): array
{
// parses all config variables
$tries = count($config);
for ($i = 0; $i < $tries; $i++) {
array_walk_recursive($config, function (&$value) use (&$config) {
if (is_string($value)) {
if (preg_match_all('/{([a-z0-9_\-\.]*)}/i', $value, $matches)) {
$variables = [];
array_walk($matches[1], function (&$variable) use (&$variables, &$config) {
$variables[$variable] = Misc::getArrayValueByKey($config, $variable, null);
});
$value = $value === $matches[0][0]
? $variables[$matches[1][0]]
: Misc::interpolate($value, $variables);
}
}
});
}
return $config;
}
/**
* Loads the configuration (directly or when available from cache) and sets class internal state.
*
* @return void
*/
protected static function load(): void
{
$configDir = static::CONFIG_DIR;
$configCacheFile = static::CONFIG_CACHE_FILE;
if (empty(static::$config)) {
if (file_exists($configCacheFile)) {
$configJson = file_get_contents($configCacheFile);
static::$config = json_decode($configJson, true);
return;
}
static::$config = self::parse(self::include($configDir));
Event::dispatch(self::ON_LOAD, [&static::$config]);
}
}
/**
* Caches the current configuration as JSON. Note that a new version will not be generated unless the cache is cleared.
*
* @return void
*/
public static function cache(): void
{
$configDir = static::CONFIG_DIR;
$configCacheFile = static::CONFIG_CACHE_FILE;
$configCacheDir = dirname($configCacheFile);
if (file_exists($configCacheFile)) {
return;
}
if (!file_exists($configCacheDir)) {
mkdir($configCacheDir, 0744, true);
}
$config = self::parse(self::include($configDir));
$configJson = json_encode($config, JSON_PRETTY_PRINT);
file_put_contents($configCacheFile, $configJson, LOCK_EX);
Event::dispatch(self::ON_CACHE);
App::log(
'Generated cache for system config, checksum (SHA-256: {checksum})',
['checksum' => hash('sha256', $configJson)],
'system'
);
}
/**
* Deletes the cached configuration JSON and resets class internal state.
*
* @return void
*/
public static function clearCache(): void
{
static::$config = [];
$configCacheFile = static::CONFIG_CACHE_FILE;
if (file_exists($configCacheFile)) {
unlink($configCacheFile);
}
Event::dispatch(self::ON_CLEAR_CACHE);
App::log('Cleared config cache', null, 'system');
}
/**
* Checks whether a value of a key exists in the configuration via dot-notation.
*
* @param string $key The dotted key representation.
*
* @return bool
*/
public static function has(string $key): bool
{
static::load();
$value = Misc::getArrayValueByKey(static::$config, $key, null);
return isset($value);
}
/**
* Gets a value of a key from the configuration via dot-notation.
*
* @param string $key The dotted key representation.
* @param mixed $fallback [optional] The default fallback value.
*
* @return mixed The requested value or null.
*/
public static function get(string $key, $fallback = null)
{
static::load();
return Misc::getArrayValueByKey(static::$config, $key, $fallback);
}
/**
* Sets a value of a key in the configuration via dot-notation.
*
* @param string $key The dotted key representation.
* @param mixed $value The value to set.
*
* @return void
*/
public static function set(string $key, $value): void
{
static::load();
Misc::setArrayValueByKey(static::$config, $key, $value);
}
/**
* Returns the currently loaded configuration.
*
* @return array
*/
public static function getAll(): array
{
static::load();
return static::getReference();
}
/**
* Returns a referenced to the current configuration array.
*
* @return array
*
* @since 1.5.5
*/
public static function &getReference(): array
{
static::load();
return static::$config;
}
}