|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Charcoal\Config; |
|
4
|
|
|
|
|
5
|
|
|
use \InvalidArgumentException; |
|
6
|
|
|
|
|
7
|
|
|
|
|
8
|
|
|
// Local namespace depeendencies |
|
9
|
|
|
use \Charcoal\Config\ConfigInterface; |
|
10
|
|
|
use \Charcoal\Config\GenericConfig; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* An implementation, as Trait, of the `ConfigurableInterface`. |
|
14
|
|
|
* |
|
15
|
|
|
* This Trait contains one additional abstract (protected) function: `create_config()` |
|
16
|
|
|
*/ |
|
17
|
|
|
trait ConfigurableTrait |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* @var ConfigInterface $config |
|
21
|
|
|
*/ |
|
22
|
|
|
private $config; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Set the object's configuration container. |
|
26
|
|
|
* |
|
27
|
|
|
* @param ConfigInterface|array $config The datas to set. |
|
28
|
|
|
* @throws InvalidArgumentException If the parameter is invalid. |
|
29
|
|
|
* @return ConfigurableInterface Chainable |
|
30
|
|
|
*/ |
|
31
|
|
|
public function setConfig($config) |
|
32
|
|
|
{ |
|
33
|
|
|
if (is_array($config)) { |
|
34
|
|
|
$this->config = $this->createConfig($config); |
|
35
|
|
|
} elseif ($config instanceof ConfigInterface) { |
|
36
|
|
|
$this->config = $config; |
|
37
|
|
|
} else { |
|
38
|
|
|
throw new InvalidArgumentException( |
|
39
|
|
|
'Configuration must be an array or a ConfigInterface object.' |
|
40
|
|
|
); |
|
41
|
|
|
} |
|
42
|
|
|
return $this; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Retrieve the object's configuration container, or one of its entry. |
|
47
|
|
|
* |
|
48
|
|
|
* If the object has no existing config, create one. |
|
49
|
|
|
* |
|
50
|
|
|
* If a key is provided, return the configuration key value instead of the full object. |
|
51
|
|
|
* |
|
52
|
|
|
* @param string $key Optional. If provided, the config key value will be returned, instead of the full object. |
|
53
|
|
|
* @see self::create_config() |
|
54
|
|
|
* @return ConfigInterface |
|
55
|
|
|
*/ |
|
56
|
|
|
public function config($key = null) |
|
57
|
|
|
{ |
|
58
|
|
|
if ($this->config === null) { |
|
59
|
|
|
$this->config = $this->createConfig(); |
|
60
|
|
|
} |
|
61
|
|
|
if ($key !== null) { |
|
62
|
|
|
return $this->config->get($key); |
|
63
|
|
|
} else { |
|
64
|
|
|
return $this->config; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* Retrieve a new ConfigInterface instance for the object. |
|
70
|
|
|
* |
|
71
|
|
|
* @see AbstractConfig::__construct() |
|
72
|
|
|
* @param array|string|null $data Optional data to pass to the new ConfigInterface instance. |
|
73
|
|
|
* @return ConfigInterface |
|
74
|
|
|
*/ |
|
75
|
|
|
protected function createConfig($data = null) |
|
76
|
|
|
{ |
|
77
|
|
|
return new GenericConfig($data); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|