-
Notifications
You must be signed in to change notification settings - Fork 1
/
BaseConfig.php
103 lines (86 loc) · 2.24 KB
/
BaseConfig.php
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
<?php
/**
* This file is part of the Cervo package.
*
* Copyright (c) 2010-2018 Nevraxe inc. & Marc André Audet <maudet@nevraxe.com>.
*
* @package Cervo
* @author Marc André Audet <maaudet@nevraxe.com>
* @copyright 2010 - 2018 Nevraxe inc. & Marc André Audet
* @license See LICENSE.md BSD-2-Clauses
* @link https://github.com/Nevraxe/Cervo
* @since 5.0.0
*/
declare(strict_types=1);
namespace Cervo\Config;
/**
* Configuration manager for Cervo.
*
* @author Marc André Audet <maudet@nevraxe.com>
*/
class BaseConfig
{
/**
* The currently set values in a multi-dimensional array.
* @var array
*/
private $values = [];
/**
* Set the value at the specified configuration path.
*
* @param string|array $name The configuration path
* @param mixed $value
*
* @return $this
*/
public function set($name, $value)
{
if (!is_array($name)) {
$name = explode('/', $name);
}
$current = &$this->values;
foreach ($name as $key) {
$current = &$current[$key];
}
$current = $value;
return $this;
}
/**
* Return the value for the specified configuration path.
* If this value is not set, return the default value.
* Return null if not set.
*
* @param string $name The configuration path
*
* @return mixed
*/
public function get(string $name)
{
$current = &$this->values;
foreach (explode('/', $name) as $key) {
if ($current[$key]) {
$current = &$current[$key];
} else {
return null;
}
}
return $current;
}
/**
* Recursively set all the values from an array.
* Usually used when importing.
*
* @param array $array
* @param array $currentPath
*/
public function setFromArrayRecursive(array $array, array $currentPath = [])
{
foreach ($array as $key => $el) {
if (is_array($el)) {
$this->setFromArrayRecursive($el, array_merge($currentPath, [$key]));
} else {
$this->set(array_merge($currentPath, [$key]), $el);
}
}
}
}