|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Northwoods\Config; |
|
5
|
|
|
|
|
6
|
|
|
/** |
|
7
|
|
|
* @param mixed $default |
|
8
|
|
|
* @return mixed |
|
9
|
|
|
*/ |
|
10
|
|
|
function array_path(array $config, string $dotPath, $default = null) |
|
|
|
|
|
|
11
|
|
|
{ |
|
12
|
|
|
// Working from the first key, descend into the array until nothing is found |
|
13
|
3 |
|
return array_reduce( |
|
14
|
3 |
|
explode('.', $dotPath), |
|
15
|
|
|
function ($config, $key) use ($default) { |
|
16
|
3 |
|
return isset($config[$key]) ? $config[$key] : $default; |
|
17
|
3 |
|
}, |
|
18
|
3 |
|
$config |
|
19
|
|
|
); |
|
20
|
|
|
} |
|
|
|
|
|
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param mixed $value |
|
24
|
|
|
*/ |
|
25
|
|
|
function array_path_set(array $config, string $dotPath, $value): array |
|
|
|
|
|
|
26
|
|
|
{ |
|
27
|
|
|
// Work backward from the last key, wrapping each key in an array |
|
28
|
3 |
|
$replace = array_reduce( |
|
29
|
3 |
|
array_reverse(explode('.', $dotPath)), |
|
30
|
|
|
function ($value, $key) { |
|
31
|
3 |
|
return [$key => $value]; |
|
32
|
3 |
|
}, |
|
33
|
3 |
|
$value |
|
34
|
|
|
); |
|
35
|
|
|
|
|
36
|
|
|
// Overwrite the array with the replacement |
|
37
|
3 |
|
return array_replace_recursive($config, $replace); |
|
38
|
|
|
} |
|
|
|
|
|
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* alternative to var_export that exports an array to short array syntax |
|
42
|
|
|
* copyright disclaimer: orignally written by stemar: [https://gist.github.com/stemar/bb7c5cd2614b21b624bf57608f995ac0] |
|
43
|
|
|
*/ |
|
44
|
|
|
function varexport($expression, $return=FALSE) { |
|
|
|
|
|
|
45
|
1 |
|
$export = var_export($expression, TRUE); |
|
|
|
|
|
|
46
|
1 |
|
$export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export); |
|
47
|
1 |
|
$array = preg_split("/\r\n|\n|\r/", $export); |
|
48
|
1 |
|
$array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => ['], $array); |
|
|
|
|
|
|
49
|
1 |
|
$export = join(PHP_EOL, array_filter(["["] + $array)); |
|
50
|
1 |
|
if ((bool)$return) return $export; else echo $export; |
|
|
|
|
|
|
51
|
|
|
} |
|
52
|
|
|
|
Learn more about camelCase.