forked from corycollier/mvc-lite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Config.php
123 lines (110 loc) · 2.86 KB
/
Config.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<?php
/**
* Registry
*
* @category PHP
* @package MvcLite
* @subpackage Config
* @since File available since release 3.0.x
* @author Cory Collier <corycollier@corycollier.com>
*/
namespace MvcLite;
use MvcLite\Traits\Singleton as SingletonTrait;
/**
* Registry
*
* Data store for application level storage
*
* @category PHP
* @package MvcLite
* @subpackage Config
* @since Class available since release 3.0.x
* @author Cory Collier <corycollier@corycollier.com>
*/
class Config extends ObjectAbstract
{
use SingletonTrait;
const MSG_ERR_BAD_CONFIG = 'Configuration not loaded. Bad file provided';
/**
* Where all the config stuff goes
*
* @var array $data
*/
protected $data = [];
/**
* Init hook.
*
* @param string|array $config A filepath to an ini file, or an array of configuration options
*
* @return MvcLite\Config Returns $this, for object-chaining.
*/
public function init($config)
{
if (!is_array($config)) {
if (!file_exists($config)) {
throw new Exception(self::MSG_ERR_BAD_CONFIG);
}
$config = parse_ini_file($config, 1);
}
$this->setAll($config);
}
/**
* Setter for data.
*
* @param string $name The name to store the value as.
* @param mixed $value The value to store.
*
* @return MvcLite\Config Returns $this, for object-chaining.
*/
public function set($name, $value)
{
$this->data[$name] = $value;
return $this;
}
/**
* Getter for data.
*
* @param string $name The name of what to get.
*
* @return MvcLite\Config Returns $this, for object-chaining.
*/
public function get($name)
{
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
}
/**
* Gets an entire section of the configuration, by name.
*
* @param string $name The section name to retreive.
*
* @return array The results of the request.
*/
public function getSection($name)
{
$results = [];
foreach ($this->data as $key => $value) {
$parts = explode('.', $key);
if ($name === $parts[0]) {
$results[$key] = $value;
}
}
return $results;
}
/**
* Assigns multiple values to the config in a single method call.
*
* @param array $values A key/value array of things to store.
*
* @return MvcLite\Config Returns $this, for object-chaining.
*/
public function setAll($params = [])
{
// itereate through the built results, setting their values to registry
foreach ($params as $setting => $values) {
$this->set($setting, $values);
}
return $this;
}
}