Add configuration helper (consolidator) class and unit tests

This commit is contained in:
Kijin Sung 2016-05-19 17:46:52 +09:00
parent a098685c29
commit 557d338427
2 changed files with 111 additions and 0 deletions

View file

@ -0,0 +1,89 @@
<?php
namespace Rhymix\Framework\Helpers;
use Rhymix\Framework\Config;
use Rhymix\Framework\Plugin;
/**
* Config helper class.
*/
class ConfigHelper
{
/**
* Cache plugin configuration during consolidation.
*/
protected static $_config_cache = array();
/**
* Consolidate configuration from multiple sources.
*
* @param array $format
* @return array
*/
public static function consolidate($format)
{
self::$_config_cache = array();
$result = array();
foreach ($format as $key => $value)
{
$result[$key] = self::_parseConfigValue((array)$value);
}
self::$_config_cache = array();
return $result;
}
/**
* Parse and get a configuration value.
*
* @param array $value
* @return mixed
*/
protected static function _parseConfigValue(array $value)
{
foreach ($value as $option)
{
$option = array_map('trim', explode(':', $option, 2));
if (count($option) === 1)
{
$result = Config::get($option[0]);
if ($result !== null)
{
return $result;
}
}
else
{
if (!isset(self::$_config_cache[$option[0]]))
{
self::$_config_cache[$option[0]] = getModel('module')->getModuleConfig($option[0]) ?: null;
}
$options = explode('.', $option[1]);
$temp = self::$_config_cache[$option[0]];
foreach ($options as $step)
{
if (is_object($temp) && isset($temp->$step))
{
$temp = $temp->$step;
}
elseif (is_array($temp) && isset($temp[$step]))
{
$temp = $temp[$step];
}
else
{
$temp = null;
}
}
if ($temp !== null)
{
return $temp;
}
}
}
return null;
}
}

View file

@ -0,0 +1,22 @@
<?php
use Rhymix\Framework\Helpers\ConfigHelper;
class ConfigHelperTest extends \Codeception\TestCase\Test
{
public function testConsolidate()
{
$member_config = getModel('module')->getModuleConfig('member');
$consolidated = ConfigHelper::consolidate(array(
'dbtype' => array('db.type', 'member:nosuchconfig'),
'member' => array('no.such.config', 'member:enable_join'),
'nosuch' => array('no.such.config', 'member:no.such.config.either'),
'single' => 'member:identifier',
));
$this->assertEquals(config('db.type'), $consolidated['dbtype']);
$this->assertEquals($member_config->enable_join, $consolidated['member']);
$this->assertNull($consolidated['nosuch']);
$this->assertEquals($member_config->identifier, $consolidated['single']);
}
}