自动在多维数组中用环境变量替换叶子值

1.0.2 2019-10-26 00:28 UTC

This package is not auto-updated.

Last update: 2024-09-23 06:19:27 UTC


README

Build Status codecov

摘要

EnvArray 允许您自动用环境变量填充数组值。它没有依赖性(除了PHPUnit用于开发和您的精神健康)。

用法

<?php

/**
 * Given the following environmental vars:
 * 
 * DB_HOST=mysql.myhost.com
 * DB_USER=webmaster
 * DB_PASS=weakpassword
 */

$envArray = new \ThreatDataScience\EnvArray\EnvArray();
$array = [
    'database' => [
        'host' => '{{DB_HOST:string:127.0.0.1}}',
        'port' => '{{DB_PORT:int:3306}}',
        'user' => '{{DB_USER:string:root}}',
        'password' => '{{DB_PASS:string:root}}'
    ]
];
$array = $envArray->fill($array);

/**
 * Will give you:
 * 
 *  [
 *    'database' => [
 *      'host' => 'mysql.myhost.com',
 *      'port' => 3306,
 *      'user' => 'webmaster',
 *      'password' => 'weakpassword'
 *    ]
 *  ];
 */

/**
 * It works with flat arrays too!
 * 
 * (Note, we don't condone this specific use case example, use a load balancer)
 * 
 * Given the following environmental vars:
 * 
 * ELASTIC_01=01.es.myhost.com
 * ELASTIC_01=02.es.myhost.com
 * ELASTIC_03=03.es.myhost.com
 */

$envArray = new \ThreatDataScience\EnvArray\EnvArray();
$array = [
    'elastic' => [
        '{{ELASTIC_01}}',
        '{{ELASTIC_02}}',
        '{{ELASTIC_03}}'
    ]
];
$array = $envArray->fill($array);

/**
 * Will give you:
 * 
 *  [
 *    'elastic' => [
 *       '01.es.myhost.com',
 *       '02.es.myhost.com',
 *       '03.es.myhost.com',
 *     ]
 *  ];
 */

环境字符串模式

{{<env var name>:<coercion type>:<default value>}}

环境变量名

环境变量名可以是 [A-Za-z0-9_-] 的任意组合,但不能仅仅是 only [-_]+

强制类型

支持的类型

  • 通过 bool 支持 Boolean
  • 通过 int 支持 Integer
  • 通过 float 支持 Float
  • 通过 string 支持 String(或者无类型,但在需要定义默认值时很有用)

默认值

任何值都可以,但存在一定的限制,比如没有对像 Default default 这样的检查。

{{DB_HOST:int:789.0909}}

默认默认值

默认默认值是 null

为什么不使用 \${.+}

使用 \${.+} 会引入太多的冲突,因为将环境变量作为字符串中的字面量传递是合理的用例。我们同意,从基本用例的角度来看,这会使事情变得更简单,但如果我们需要支持表示我们想要 保留 字面字符串而不是解析它的复杂度,那么项目的复杂度会大幅增加。

“源代码的修改”

代码在 ./src 中,测试在 ./tests 中。

我们欢迎贡献、建议和错误报告,但如果我们打开一个工单,我们要求您尽可能详细,以保持事情简洁。我们还维护100%的代码覆盖率,所以带有测试的PR是极好的。