first commit

This commit is contained in:
Your Name
2026-01-19 14:19:22 +08:00
commit fe2d9c1868
4777 changed files with 665503 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
name: PHP Composer
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ${{ matrix.operating-system }}
strategy:
matrix:
operating-system: [ ubuntu-18.04 ]
php: [ '5.4', '5.5', '5.6', '7.1', '7.2', '7.3', '7.4' ]
name: PHP ${{ matrix.php }}@${{ matrix.operating-system }}
steps:
- uses: actions/checkout@v2
- uses: shivammathur/setup-php@master
with:
php-version: ${{ matrix.php }}
extensions: xdebug
- name: check php version
run: php --version
- name: check composer version
run: composer --version
- name: Validate composer.json and composer.lock
run: composer validate
- name: Install dependencies
run: composer install --prefer-dist --no-progress
- name: Run test suite
run: ./vendor/bin/phpunit
- name: Upload coverage results to Coveralls
env:
COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_TOKEN }}
run: ./vendor/bin/coveralls --coverage_clover=build/logs/clover.xml -v

View File

@@ -0,0 +1,3 @@
composer.phar
vendor
testsdata/phpunit_*

View File

@@ -0,0 +1,143 @@
[![PHP Composer](https://github.com/clagiordano/weblibs-configmanager/actions/workflows/php.yml/badge.svg)](https://github.com/clagiordano/weblibs-configmanager/actions/workflows/php.yml)
[![Coverage Status](https://coveralls.io/repos/github/clagiordano/weblibs-configmanager/badge.svg?branch=master)](https://coveralls.io/github/clagiordano/weblibs-configmanager?branch=master)
[![SymfonyInsight](https://insight.symfony.com/projects/54c4e80c-ff15-4235-8bec-a4c71bbe3ba5/mini.svg)](https://insight.symfony.com/projects/54c4e80c-ff15-4235-8bec-a4c71bbe3ba5)
# weblibs-configmanager
weblibs-configmanager is a tool library for easily read and access to php config array file and direct read/write configuration file / object.
## Why use weblibs-configmanager ?
The purpose of this project is to propose a simple and lightweight library to manage php hierarchical configuration files.
## Supported formats
This package supports config files in the following format:
Format | Component | Since version | Description
:---: | :---: | :---: | ---
Array | `ConfigManager` | `v0.1.0` | Deprecated, legacy name for the php array reader, only for compatibility support
Array | `ArrayConfigManager` | `v1.2.0` | A file that returns a php array, the original supported format
Yaml | `YamlConfigManager` | `v1.3.0` | A file containing a valid YAML file
JSON | `JsonConfigManager` | `v1.4.0` | A file containing a valid JSON file
All the supported format are parsed and internally handled in the same way granting the same functionalities.
## Installation
The recommended way to install weblibs-configmanager is through [Composer](https://getcomposer.org).
```bash
composer require clagiordano/weblibs-configmanager
```
## Usage examples (Array format)
### Write a sample config file like this
```php
<?php
return array (
'app' => 'app_name',
'db' =>
array (
'host' => 'localhost',
'user' => 'sample_user',
'pass' => 'sample_pass',
'port' => 3306,
),
'other' =>
array (
'multi' =>
array (
'deep' =>
array (
'nested' => 'config_value',
),
),
),
);
```
### Instance ConfigManager object
```php
use clagiordano\weblibs\configmanager\ConfigManager;
/**
* Instance object to read argument file
*/
$config = new ConfigManager("configfile.php");
```
### Check if a value exists into config file
```php
/**
* Check if a value exists into config file
*/
$value = $config->existValue('app');
```
### Read a simple element from config file
```php
/**
* Read a simple element from config file
*/
$value = $config->getValue('app');
```
### Access to a nested element from config
```php
/**
* Access to a nested element from config
*/
$nestedValue = $config->getValue('other.multi.deep.nested');
```
### Change config value at runtime
```php
/**
* Change config value at runtime
*/
$this->config->setValue('other.multi.deep.nested', "SUPERNESTED");
```
### Save config file with original name (OVERWRITE)
```php
/**
* Save config file with original name (OVERWRITE)
*/
$this->config->saveConfigFile();
```
### Or save config file with a different name
```php
/**
* Save config file with original name (OVERWRITE)
*/
$this->config->saveConfigFile('/new/file/name/or/path/test.php');
```
### Optionally you can also reload config file from disk after save
```php
/**
* Optionally you can also reload config file from disk after save
*/
$this->config->saveConfigFile('/new/file/name/or/path/test.php', true);
```
### Load another configuration file without reinstance ConfigManager
```php
/**
* Load another configuration file without reinstance ConfigManager
*/
$this->config->loadConfig('another_config_file.php');
```
## Legal
*Copyright (C) Claudio Giordano <claudio.giordano@autistici.org>*

View File

@@ -0,0 +1,51 @@
{
"name": "clagiordano/weblibs-configmanager",
"description": "weblibs-configmanager is a tool library for easily read and access to php config array file and direct read/write configuration file / object",
"type": "library",
"license": "LGPL-3.0-or-later",
"keywords": ["clagiordano", "weblibs", "configuration", "manager", "tool"],
"authors": [
{
"name": "Claudio Giordano",
"email": "claudio.giordano@autistici.org",
"role": "Developer"
}
],
"autoload": {
"psr-4": {
"clagiordano\\weblibs\\configmanager\\": "src/"
}
},
"require": {
"php": ">=5.4",
"symfony/yaml": "^2.8",
"ext-json": "*"
},
"require-dev": {
"phpunit/phpunit": "^4.8",
"clagiordano/phpunit-result-printer": "^1",
"php-coveralls/php-coveralls": "^1.1"
},
"autoload-dev": {
"psr-4": {
"clagiordano\\weblibs\\configmanager\\tests\\": "tests/",
"clagiordano\\weblibs\\configmanager\\testdata\\": "testdata/"
}
},
"scripts": {
"test": [
"Composer\\Config::disableProcessTimeout",
"./vendor/bin/phpunit --no-coverage"
],
"coverage": [
"Composer\\Config::disableProcessTimeout",
"php -dzend_extension=xdebug.so ./vendor/bin/phpunit"
],
"debug": "php -dxdebug.remote_autostart=On -dzend_extension=xdebug.so ./vendor/bin/phpunit"
},
"config": {
"platform": {
"php": "5.4"
}
}
}

1713
vendor/clagiordano/weblibs-configmanager/composer.lock generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
verbose="true"
printerClass="clagiordano\PhpunitResultPrinter\ResultPrinter"
>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
<php>
<ini name="display_errors" value="On"/>
<ini name="error_reporting" value="E_ALL"/>
<ini name="display_startup_errors" value="On"/>
</php>
<logging>
<log type="coverage-html" target="build/coverage/"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
<log type="coverage-crap4j" target="build/logs/crap4j.xml"/>
<log type="junit" target="build/logs/junit.xml"/>
<log type="coverage-text" target="build/logs/coverage.txt" showUncoveredFiles="true" />
</logging>
</phpunit>

View File

@@ -0,0 +1,159 @@
<?php
namespace clagiordano\weblibs\configmanager;
use Exception;
use RuntimeException;
/**
* Class AbstractConfigManager
* @package clagiordano\weblibs\configmanager
*/
abstract class AbstractConfigManager implements IConfigurable
{
/** @var array $configData */
protected $configData = null;
/** @var string $configFilePath */
protected $configFilePath = null;
/**
* Create config object, optionally automatic load config
* from argument $configFilePath
*
* @param string $configFilePath
*/
public function __construct($configFilePath = null)
{
try {
$this->loadConfig($configFilePath);
} catch (Exception $exception) {
/**
* Allow not existent file name at construct
*/
}
}
/**
* Get value pointer from config for get/set value
*
* @param string $configPath
*
* @return mixed
*/
protected function & getValuePointer($configPath)
{
$configData =& $this->configData;
$parts = explode('.', $configPath);
$length = count($parts);
for ($i = 0; $i < $length; $i++) {
if (!isset($configData[ $parts[ $i ] ])) {
$configData[ $parts[ $i ] ] = ($i === $length) ? [] : null;
}
$configData = &$configData[ $parts[ $i ] ];
}
return $configData;
}
/**
* Get value from config data throught keyValue path
*
* @param string $configPath
* @param mixed $defaultValue
*
* @return mixed
*/
public function getValue($configPath, $defaultValue = null)
{
$stored = $this->getValuePointer($configPath);
return (is_null($stored)
? $defaultValue
: $stored);
}
/**
* Check if exist required config for keyValue
*
* @param string $keyValue
*
* @return mixed
*/
public function existValue($keyValue)
{
return !is_null($this->getValue($keyValue));
}
/**
* Set value in config path
*
* @param string $configPath
* @param mixed $newValue
*
* @return IConfigurable
*/
public function setValue($configPath, $newValue)
{
$configData = &$this->getValuePointer($configPath);
$configData = $newValue;
return $this;
}
/**
* @inheritDoc
*/
public function getConfig()
{
return $this->configData;
}
/**
* @inheritDoc
*/
public function setConfig($config)
{
$this->configData = (array)$config;
return $this;
}
/**
* @inheritDoc
*/
public function convert(IConfigurable $target)
{
$target->setConfig($this->getConfig());
return $target;
}
/**
* Check if configFilePath exists and is readable
* @return bool
* @throws RuntimeException
*/
protected function checkLoadable()
{
if ($this->configFilePath !== null) {
if (file_exists($this->configFilePath) && is_readable($this->configFilePath)) {
/**
* Readable
*/
return true;
}
/**
* $configFilePath is not null, but not existent or not readable
*/
throw new RuntimeException("Failed to read config file from path '{$this->configFilePath}'");
}
/**
* $configFilePath is null
*/
return false;
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace clagiordano\weblibs\configmanager;
use Exception;
use RuntimeException;
/**
* Class ArrayConfigManager, class for easily read and access to php config array file.
* @package clagiordano\weblibs\configmanager
*/
class ArrayConfigManager extends AbstractConfigManager
{
/**
* Load config data from file and store it into internal property
*
* @param null|string $configFilePath
*
* @return IConfigurable
*/
public function loadConfig($configFilePath = null)
{
$this->configFilePath = $configFilePath;
if ($this->checkLoadable()) {
$this->configData = require $this->configFilePath;
}
return $this;
}
/**
* Prepare and write config file on disk
*
* @param null|string $configFilePath
* @param bool $autoReloadConfig
*
* @return IConfigurable
* @throws RuntimeException
*/
public function saveConfigFile($configFilePath = null, $autoReloadConfig = false)
{
if (is_null($configFilePath)) {
$configFilePath = $this->configFilePath;
}
$configFileContent = "<?php\n\n";
$configFileContent .= "return ";
$configFileContent .= var_export($this->configData, true);
$configFileContent .= ";\n\n";
try {
file_put_contents($configFilePath, $configFileContent);
if (is_callable('opcache_invalidate')) {
/**
* Invalidate opcache for writed file if opcache is available
*/
opcache_invalidate($configFilePath, true);
}
} catch (Exception $exception) {
throw new RuntimeException(
"Failed to write config file to path '{$configFilePath}'\n{$exception->getMessage()}"
);
}
if ($autoReloadConfig) {
$this->loadConfig($configFilePath);
}
return $this;
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace clagiordano\weblibs\configmanager;
/**
* Class ConfigManager, class for easily read and access to php config array file.
* @package clagiordano\weblibs\configmanager
* @deprecated This is a wrapper for the same class with the new name,
* please use directly ArrayConfigManager instead
*/
class ConfigManager extends ArrayConfigManager
{
}

View File

@@ -0,0 +1,28 @@
<?php
namespace clagiordano\weblibs\configmanager;
/**
* Class FileConverter
* @package clagiordano\weblibs\configmanager
*/
class FileConverter implements IConvertable
{
/**
* @inheritDoc
*/
public static function convert(IConfigurable $source, IConfigurable $target)
{
return $target->setConfig($source->getConfig());
}
/**
* @inheritDoc
*/
public static function convertAndSave(IConfigurable $source, IConfigurable $target)
{
$target->setConfig($source->getConfig());
return $target->saveConfigFile();
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace clagiordano\weblibs\configmanager;
use RuntimeException;
/**
* Class ConfigManager, class for easily read and access to php config array file.
* @package clagiordano\weblibs\configmanager
*/
interface IConfigurable
{
/**
* Load config data from file and store it into internal property
*
* @param null|string $configFilePath
*
* @return IConfigurable
*/
public function loadConfig($configFilePath = null);
/**
* Prepare and write config file on disk
*
* @param null|string $configFilePath
* @param bool $autoReloadConfig
*
* @return IConfigurable
* @throws RuntimeException
*/
public function saveConfigFile($configFilePath = null, $autoReloadConfig = false);
/**
* Get value from config data throught keyValue path
*
* @param string $configPath
* @param mixed $defaultValue
*
* @return mixed
*/
public function getValue($configPath, $defaultValue = null);
/**
* Check if exist required config for keyValue
*
* @param string $keyValue
*
* @return mixed
*/
public function existValue($keyValue);
/**
* Set value in config path
*
* @param string $configPath
* @param mixed $newValue
*
* @return IConfigurable
*/
public function setValue($configPath, $newValue);
/**
* Returns the whole internal configuration as array
* @return array
*/
public function getConfig();
/**
* Sets the whole internal configuration from array
*
* @param array $config
* @return IConfigurable
*/
public function setConfig($config);
/**
* Converts the current instance into another one provided as argument,
* migrating its internal configuration and returning the new one.
*
* @param IConfigurable $target
* @return IConfigurable
*/
public function convert(IConfigurable $target);
}

View File

@@ -0,0 +1,28 @@
<?php
namespace clagiordano\weblibs\configmanager;
/**
* Class FileConverter
* @package clagiordano\weblibs\configmanager
*/
interface IConvertable
{
/**
* Converts source config to target config format
*
* @param IConfigurable $source
* @param IConfigurable $target
* @return IConfigurable
*/
public static function convert(IConfigurable $source, IConfigurable $target);
/**
* Converts source config to target config format and save it on target config file
*
* @param IConfigurable $source
* @param IConfigurable $target
* @return IConfigurable
*/
public static function convertAndSave(IConfigurable $source, IConfigurable $target);
}

View File

@@ -0,0 +1,68 @@
<?php
namespace clagiordano\weblibs\configmanager;
use Exception;
use RuntimeException;
/**
* Class JsonConfigManager
* @package clagiordano\weblibs\configmanager
*/
class JsonConfigManager extends AbstractConfigManager
{
/**
* Load config data from file and store it into internal property
*
* @param null|string $configFilePath
*
* @return IConfigurable
*/
public function loadConfig($configFilePath = null)
{
$this->configFilePath = $configFilePath;
if ($this->checkLoadable()) {
if (!is_callable('json_decode')) {
throw new RuntimeException('Missing php-json extension');
}
$this->configData = json_decode(file_get_contents($configFilePath), true);
}
return $this;
}
/**
* Prepare and write config file on disk
*
* @param null|string $configFilePath
* @param bool $autoReloadConfig
*
* @return IConfigurable
* @throws RuntimeException
*/
public function saveConfigFile($configFilePath = null, $autoReloadConfig = false)
{
if (is_null($configFilePath)) {
$configFilePath = $this->configFilePath;
}
try {
if (!is_callable('json_encode')) {
throw new RuntimeException('Missing php-json extension');
}
file_put_contents($configFilePath, json_encode($this->configData, JSON_UNESCAPED_UNICODE));
} catch (Exception $exception) {
throw new RuntimeException(
"Failed to write config file to path '{$configFilePath}'\n{$exception->getMessage()}"
);
}
if ($autoReloadConfig) {
$this->loadConfig($configFilePath);
}
return $this;
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace clagiordano\weblibs\configmanager;
use Exception;
use RuntimeException;
use Symfony\Component\Yaml\Yaml;
/**
* Class YamlConfigManager
* @package clagiordano\weblibs\configmanager
*/
class YamlConfigManager extends AbstractConfigManager
{
/**
* Load config data from file and store it into internal property
*
* @param null|string $configFilePath
*
* @return IConfigurable
*/
public function loadConfig($configFilePath = null)
{
$this->configFilePath = $configFilePath;
if ($this->checkLoadable()) {
$this->configData = Yaml::parse(file_get_contents($configFilePath));
}
return $this;
}
/**
* Prepare and write config file on disk
*
* @param null|string $configFilePath
* @param bool $autoReloadConfig
*
* @return IConfigurable
* @throws RuntimeException
*/
public function saveConfigFile($configFilePath = null, $autoReloadConfig = false)
{
if (is_null($configFilePath)) {
$configFilePath = $this->configFilePath;
}
try {
file_put_contents(
$configFilePath,
Yaml::dump($this->configData, 2, 2)
);
} catch (Exception $exception) {
throw new RuntimeException(
"Failed to write config file to path '{$configFilePath}'\n{$exception->getMessage()}"
);
}
if ($autoReloadConfig) {
$this->loadConfig($configFilePath);
}
return $this;
}
}

View File

@@ -0,0 +1,223 @@
<?php
namespace clagiordano\weblibs\configmanager\tests;
use clagiordano\weblibs\configmanager\IConfigurable;
use PHPUnit\Framework\TestCase;
/**
* Class AbstractConfigManagerTest
* @package clagiordano\weblibs\configmanager\tests
*/
abstract class AbstractConfigManagerTest extends TestCase
{
/** @var string $configFile */
protected $configFile = null;
/** @var IConfigurable $config */
protected $config = null;
public static function setUpBeforeClass()
{
parent::setUpBeforeClass();
/**
* Remove temp dir
*/
shell_exec("rm -rf " . __DIR__ . '/../testsdata/temp');
/**
* Create temp dir
*/
$status = mkdir(__DIR__ . '/../testsdata/temp/');
self::assertTrue($status);
}
public static function tearDownAfterClass()
{
parent::tearDownAfterClass();
/**
* Remove temp dir
*/
shell_exec("rm -rf " . __DIR__ . '/../testsdata/temp');
}
public function testBasicUsage()
{
$this->assertNotNull(
$this->config->getValue('app')
);
}
public function testFastUsage()
{
$this->assertNotNull(
$this->config->getValue('app')
);
}
public function testFastInvalidKey()
{
$this->assertNull(
$this->config->getValue('invalidKey')
);
}
public function testFastInvalidKeyWithDefault()
{
$this->assertEquals(
$this->config->getValue('invalidKey', 'defaultValue'),
'defaultValue'
);
}
public function testFastNestedConfig()
{
$this->assertNotNull(
$this->config->getValue('other.multi.deep.nested')
);
}
public function testCheckExistConfig()
{
$this->assertTrue(
$this->config->existValue('other.multi.deep.nested')
);
}
public function testCheckNotExistConfig()
{
$this->assertFalse(
$this->config->existValue('invalid.config.path')
);
}
public function testSetValue()
{
$this->config->setValue('other.multi.deep.nested', __FUNCTION__);
$this->assertEquals(
$this->config->getValue('other.multi.deep.nested'),
__FUNCTION__
);
}
public function testFailedSaveConfig()
{
$this->setExpectedException('Exception');
$this->config->saveConfigFile('/invalid/path');
}
public function testSuccessSaveConfigOnTempAndReload()
{
$this->config->setValue('other.multi.deep.nested', "SUPERNESTED");
$this->config->saveConfigFile("/tmp/testconfig.sample", true);
$this->assertEquals(
$this->config->getValue('other.multi.deep.nested'),
"SUPERNESTED"
);
}
public function testOverwriteSameConfigFile()
{
$this->config->saveConfigFile();
}
public function testFailWriteConfig()
{
$this->setExpectedException('\RuntimeException');
$this->config->saveConfigFile('/invalid/path/test.sample');
}
/**
* @test
* @group permissions
*/
public function canRaiseExceptionOnUnreadableFile()
{
/**
* Create new temp file
*/
$testFile = tempnam(__DIR__ . '/../testsdata/temp/', 'phpunit_');
self::assertFileExists($testFile);
/**
* Make tempfile unreadable by everyone, but still writeable
*/
$status = chmod($testFile, 0200);
self::assertTrue($status);
/**
* Check permissions it must be 0200 ( --w------- )
*/
$filePerms = (fileperms($testFile) & 0777);
self::assertSame(0200, $filePerms);
/**
* Try to read that file, an exception must be thrown
*/
self::setExpectedException('\RuntimeException');
$this->config->loadConfig($testFile);
/**
* Remove temp file
*/
$status = chmod($testFile, 0744);
self::assertTrue($status);
$filePerms = (fileperms($testFile) & 0777);
self::assertSame(0755, $filePerms);
$status = unlink($testFile);
self::assertTrue($status);
self::assertFileNotExists($testFile);
}
/**
* @return array
*/
public function configDataProvider()
{
return [
[
__DIR__ . '/../testsdata/sample_config_data.converted.yml',
'\clagiordano\weblibs\configmanager\YamlConfigManager',
],
[
__DIR__ . '/../testsdata/sample_config_data.converted.json',
'\clagiordano\weblibs\configmanager\JsonConfigManager',
],
[
__DIR__ . '/../testsdata/sample_config_data.converted.php',
'\clagiordano\weblibs\configmanager\ArrayConfigManager',
],
];
}
/**
* @test
* @dataProvider configDataProvider
* @param mixed $targetConfig
* @param mixed $targetInstance
*/
public function canConvertOneFormatToAnother($targetConfig, $targetInstance)
{
if (file_exists($targetConfig)) {
/**
* Drop target file if already existing
*/
unlink($targetConfig);
}
self::assertFileNotExists($targetConfig);
$target = new $targetInstance($targetConfig);
self::assertInstanceOf($targetInstance, $target);
$converted = $this->config->convert($target);
self::assertInstanceOf($targetInstance, $converted);
self::assertFileNotExists($targetConfig);
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace clagiordano\weblibs\configmanager\tests;
use clagiordano\weblibs\configmanager\ArrayConfigManager;
/**
* Class ArrayConfigManagerTest
* @package clagiordano\weblibs\configmanager\tests
*/
class ArrayConfigManagerTest extends AbstractConfigManagerTest
{
protected $configFile = 'testsdata/sample_config_data.php';
public function setUp()
{
parent::setUp();
$this->config = new ArrayConfigManager("TestConfigData.php");
$this->assertInstanceOf('clagiordano\weblibs\configmanager\ArrayConfigManager', $this->config);
$this->assertFileExists($this->configFile);
$this->config->loadConfig($this->configFile);
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace clagiordano\weblibs\configmanager\tests;
use clagiordano\weblibs\configmanager\ConfigManager;
/**
* Class ConfigManagerTest
* @package clagiordano\weblibs\configmanager\tests
*/
class ConfigManagerTest extends AbstractConfigManagerTest
{
protected $configFile = 'testsdata/sample_config_data.php';
public function setUp()
{
parent::setUp();
$this->config = new ConfigManager("TestConfigData.php");
$this->assertInstanceOf('clagiordano\weblibs\configmanager\ConfigManager', $this->config);
$this->assertFileExists($this->configFile);
$this->config->loadConfig($this->configFile);
}
}

View File

@@ -0,0 +1,148 @@
<?php
namespace clagiordano\weblibs\configmanager\tests;
use clagiordano\weblibs\configmanager\ArrayConfigManager;
use clagiordano\weblibs\configmanager\FileConverter;
use clagiordano\weblibs\configmanager\YamlConfigManager;
use PHPUnit\Framework\TestCase;
/**
* Class FileConverterTest
* @package clagiordano\weblibs\configmanager\tests
*/
class FileConverterTest extends TestCase
{
/**
* @return array
*/
public function configDataProvider()
{
return [
[
__DIR__ . '/../testsdata/sample_config_data.php',
'\clagiordano\weblibs\configmanager\ArrayConfigManager',
__DIR__ . '/../testsdata/sample_config_data.php.converted.yml',
'\clagiordano\weblibs\configmanager\YamlConfigManager',
],
[
__DIR__ . '/../testsdata/sample_config_data.php',
'\clagiordano\weblibs\configmanager\ArrayConfigManager',
__DIR__ . '/../testsdata/sample_config_data.php.converted.json',
'\clagiordano\weblibs\configmanager\JsonConfigManager',
],
[
__DIR__ . '/../testsdata/sample_config_data.yml',
'\clagiordano\weblibs\configmanager\YamlConfigManager',
__DIR__ . '/../testsdata/sample_config_data.yml.converted.json',
'\clagiordano\weblibs\configmanager\JsonConfigManager',
],
[
__DIR__ . '/../testsdata/sample_config_data.yml',
'\clagiordano\weblibs\configmanager\YamlConfigManager',
__DIR__ . '/../testsdata/sample_config_data.yml.converted.php',
'\clagiordano\weblibs\configmanager\ArrayConfigManager',
],
[
__DIR__ . '/../testsdata/sample_config_data.json',
'\clagiordano\weblibs\configmanager\JsonConfigManager',
__DIR__ . '/../testsdata/sample_config_data.json.converted.yml',
'\clagiordano\weblibs\configmanager\YamlConfigManager',
],
[
__DIR__ . '/../testsdata/sample_config_data.json',
'\clagiordano\weblibs\configmanager\JsonConfigManager',
__DIR__ . '/../testsdata/sample_config_data.json.converted.php',
'\clagiordano\weblibs\configmanager\ArrayConfigManager',
],
];
}
/**
* @test
* @dataProvider configDataProvider
* @param mixed $sourceConfig
* @param mixed $sourceInstance
* @param mixed $targetConfig
* @param mixed $targetInstance
*/
public function canConvertOneFormatToAnother($sourceConfig, $sourceInstance, $targetConfig, $targetInstance)
{
if (file_exists($targetConfig)) {
/**
* Drop target file if already existing
*/
unlink($targetConfig);
}
$source = new $sourceInstance($sourceConfig);
self::assertInstanceOf($sourceInstance, $source);
$target = new $targetInstance($targetConfig);
self::assertInstanceOf($targetInstance, $target);
$converted = FileConverter::convert($source, $target);
self::assertInstanceOf($targetInstance, $converted);
$converted = FileConverter::convertAndSave($source, $target);
self::assertInstanceOf($targetInstance, $converted);
self::assertFileExists($targetConfig);
}
/**
* @test
*/
public function canSuccessConversionOnInvalidSource()
{
$source = new ArrayConfigManager();
$target = new YamlConfigManager(__DIR__ . '/../testsdata/sample_config_data.empty.converted.yml');
$converted = FileConverter::convert($source, $target);
self::assertInstanceOf('\clagiordano\weblibs\configmanager\YamlConfigManager', $converted);
self::assertSame($target, $converted);
}
/**
* @test
*/
public function canSuccessConversionAndSaveOnInvalidSource()
{
$source = new ArrayConfigManager();
$target = new YamlConfigManager(__DIR__ . '/../testsdata/sample_config_data.empty.converted.yml');
$converted = FileConverter::convertAndSave($source, $target);
self::assertInstanceOf('\clagiordano\weblibs\configmanager\YamlConfigManager', $converted);
self::assertSame($target, $converted);
}
/**
* @test
*/
public function cannotFailConversionOnInvalidTarget()
{
$source = new ArrayConfigManager(__DIR__ . '/../testsdata/sample_config_data.php');
$target = new YamlConfigManager();
$converted = FileConverter::convert($source, $target);
self::assertInstanceOf('\clagiordano\weblibs\configmanager\YamlConfigManager', $converted);
}
/**
* @test
*/
public function canFailConversionAndSaveOnInvalidTarget()
{
self::setExpectedException('\RuntimeException');
$source = new ArrayConfigManager(__DIR__ . '/../testsdata/sample_config_data.php');
$target = new YamlConfigManager();
$converted = FileConverter::convertAndSave($source, $target);
self::assertInstanceOf('\clagiordano\weblibs\configmanager\YamlConfigManager', $converted);
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace clagiordano\weblibs\configmanager\tests;
use clagiordano\weblibs\configmanager\JsonConfigManager;
/**
* Class JsonConfigManagerTest
* @package clagiordano\weblibs\configmanager\tests
*/
class JsonConfigManagerTest extends AbstractConfigManagerTest
{
protected $configFile = 'testsdata/sample_config_data.json';
public function setUp()
{
parent::setUp();
$this->config = new JsonConfigManager("TestConfigData.json");
$this->assertInstanceOf('clagiordano\weblibs\configmanager\JsonConfigManager', $this->config);
$this->assertFileExists($this->configFile);
$this->config->loadConfig($this->configFile);
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace clagiordano\weblibs\configmanager\tests;
use clagiordano\weblibs\configmanager\YamlConfigManager;
/**
* Class YamlConfigManagerTest
* @package clagiordano\weblibs\configmanager\tests
*/
class YamlConfigManagerTest extends AbstractConfigManagerTest
{
protected $configFile = 'testsdata/sample_config_data.yml';
public function setUp()
{
parent::setUp();
$this->config = new YamlConfigManager("TestConfigData.yml");
$this->assertInstanceOf('clagiordano\weblibs\configmanager\YamlConfigManager', $this->config);
$this->assertFileExists($this->configFile);
$this->config->loadConfig($this->configFile);
}
}

View File

@@ -0,0 +1 @@
{"app":"name","db":{"host":"localhost","user":"sample_user","pass":"sample_pass","port":"3306"},"other":{"multi":{"deep":{"nested":"config_value"}}}}

View File

@@ -0,0 +1,23 @@
<?php
return array (
'app' => 'name',
'db' =>
array (
'host' => 'localhost',
'user' => 'sample_user',
'pass' => 'sample_pass',
'port' => '3306',
),
'other' =>
array (
'multi' =>
array (
'deep' =>
array (
'nested' => 'config_value',
),
),
),
);

View File

@@ -0,0 +1,8 @@
app: name
db:
host: localhost
user: sample_user
pass: sample_pass
port: '3306'
other:
multi: { deep: { nested: config_value } }

View File

@@ -0,0 +1,23 @@
<?php
return array (
'app' => 'app_name',
'db' =>
array (
'host' => 'localhost',
'user' => 'sample_user',
'pass' => 'sample_pass',
'port' => 3306,
),
'other' =>
array (
'multi' =>
array (
'deep' =>
array (
'nested' => 'config_value',
),
),
),
);

View File

@@ -0,0 +1 @@
{"app":"app_name","db":{"host":"localhost","user":"sample_user","pass":"sample_pass","port":3306},"other":{"multi":{"deep":{"nested":"config_value"}}}}

View File

@@ -0,0 +1,8 @@
app: app_name
db:
host: localhost
user: sample_user
pass: sample_pass
port: 3306
other:
multi: { deep: { nested: config_value } }

View File

@@ -0,0 +1,8 @@
app: name
db:
host: localhost
user: sample_user
pass: sample_pass
port: 3306
other:
multi: { deep: { nested: config_value } }

View File

@@ -0,0 +1 @@
{"app":"name","db":{"host":"localhost","user":"sample_user","pass":"sample_pass","port":3306},"other":{"multi":{"deep":{"nested":"config_value"}}}}

View File

@@ -0,0 +1,23 @@
<?php
return array (
'app' => 'name',
'db' =>
array (
'host' => 'localhost',
'user' => 'sample_user',
'pass' => 'sample_pass',
'port' => 3306,
),
'other' =>
array (
'multi' =>
array (
'deep' =>
array (
'nested' => 'config_value',
),
),
),
);