|
1
|
|
|
<?php |
|
2
|
|
|
namespace Consolidation\Config\Inject; |
|
3
|
|
|
|
|
4
|
|
|
use Consolidation\Config\Util\ConfigMerge; |
|
5
|
|
|
|
|
6
|
|
|
/** |
|
7
|
|
|
* Given an object that contains configuration methods, inject any |
|
8
|
|
|
* configuration found in the configuration file. |
|
9
|
|
|
* |
|
10
|
|
|
* The proper use for this method is to call setter methods of the |
|
11
|
|
|
* provided object. Using configuration to call methods that do work |
|
12
|
|
|
* is an abuse of this mechanism. |
|
13
|
|
|
*/ |
|
14
|
|
|
class ConfigForSetters |
|
15
|
|
|
{ |
|
16
|
|
|
protected $config; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct($config, $group, $prefix = '', $postfix = '') |
|
19
|
|
|
{ |
|
20
|
|
|
if (!empty($group) && empty($postfix)) { |
|
21
|
|
|
$postfix = '.'; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
$this->config = new ConfigMerge($config, $group, $prefix, $postfix); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public function apply($object, $configurationKey) |
|
28
|
|
|
{ |
|
29
|
|
|
$settings = $this->config->get($configurationKey); |
|
30
|
|
|
foreach ($settings as $setterMethod => $args) { |
|
31
|
|
|
$fn = [$object, $setterMethod]; |
|
32
|
|
|
if (is_callable($fn)) { |
|
33
|
|
|
$result = call_user_func_array($fn, (array)$args); |
|
34
|
|
|
|
|
35
|
|
|
// We require that $fn must only be used with setter methods. |
|
36
|
|
|
// Setter methods are required to always return $this so that |
|
37
|
|
|
// they may be chained. We will therefore throw an exception |
|
38
|
|
|
// for any setter that returns something else. |
|
39
|
|
|
if ($result != $object) { |
|
40
|
|
|
$methodDescription = get_class($object) . "::$setterMethod"; |
|
41
|
|
|
$propertyDescription = $this->config->describe($configurationKey); |
|
42
|
|
|
throw new \Exception("$methodDescription did not return '\$this' when processing $propertyDescription."); |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
|