cupoftea/config-editor

以编程方式编辑基于数组的PHP配置文件。

v1.0.1 2021-02-07 00:54 UTC

This package is auto-updated.

Last update: 2024-09-07 08:46:06 UTC


README

以编程方式编辑基于数组的PHP配置文件。

安装

Config Editor可以通过使用Composer的require命令进行安装。

$ composer require cupoftea/config-editor

使用方法

基本示例

/**
 * Config Editor does not include file read & write operations
 * and must be passed a string representing the file contents.
 */
$config = file_get_contents('config/my_config.php');
$editor = new \CupOfTea\Config\Editor($config);

// Values can be set by passing a key and a value, or passing it an associative array with the values you want to set.
// Editor::set() returns the editor instance for easy chaining.
$editor->set('foo', 'bar')
    ->set(['baz' => 'qux', 'quux' => 'quuz']);

// Nested values can be set using array "dot" notation
$editor->set('paths.views', 'resources/views')
    ->set('paths.lang', 'resources/lang');

// Use the unset() method to completely remove a key from the configuration.
$editor->unset('foo')
    ->unset(['baz', 'quux']);

// Once you are done making edits, you can compile the config back to a string and write it to a file.
$newConfig = $editor->compile();
file_put_contents('config/my_edited_config.php', $newConfig);

配置文件

配置文件必须返回一个数组。数组不能在运行时计算。

当使用无效的配置文件时,Editor::compile()方法将抛出CupOfTea\Config\InvalidConfigurationException

有效

<?php

use Illuminate\Support\Arr;

function env($key, $default = null) {
    return $_ENV[$key] ?? $default;
}

return [
    'computed_val' => Arr::get($_SERVER, 'DOCUMENT_ROOT'),
    'env_val' => env('HOME'),
    'string' => 'str',
];

无效

<?php

function cfg($arr) {
    return $arr;
}

return cfg(['foo' => 'bar']);

无效键

Config Editor不允许在没有数组值的键上设置嵌套值,如果在编译时尝试这样做,将抛出异常。

$config = <<<'CODE'
<?php

return ['foo' => ['bar' => 'baz']];
CODE;
$editor = new \CupOfTea\Config\Editor($config);

// throws \CupOfTea\Config\InvalidKeyException
$editor->set('foo.bar.baz', 'qux')->compile();

// throws \CupOfTea\Config\InvalidKeyException
$editor
    ->set('paths', 'string')
    ->set('paths.config', 'configs/')
    ->compile();