2 namespace Consolidation\Config\Inject;
4 use Consolidation\Config\Util\ConfigMerge;
7 * Given an object that contains configuration methods, inject any
8 * configuration found in the configuration file.
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.
14 class ConfigForSetters
18 public function __construct($config, $group, $prefix = '', $postfix = '')
20 if (!empty($group) && empty($postfix)) {
24 $this->config = new ConfigMerge($config, $group, $prefix, $postfix);
27 public function apply($object, $configurationKey)
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);
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.");